Reut
Reut

Reputation: 1592

Change the legend enteries by column values in matplotlib

I'm struggling a lot with changing the labels in the legend in matplotlib charts. This is my graph: enter image description here

I would like to change the legend so the labels will be based on the values in column called "name",from the column name.

This is how I created the original graph:

ax = plt.figure()
df.iloc[3000:3005,:].loc[:,float_cols].T.plot(figsize=(10,6))
plt.title('title',size=(20))
plt.ylabel('Y', size=(14))
plt.xlabel('x', size=(14))

This is how I have tried to change the legend to the column name:

targets = df['name']

ax = plt.figure()
df.iloc[3000:3005,:].loc[:,float_cols].T.plot(figsize=(10,6).label=targets)
plt.title('title',size=(20))
plt.ylabel('Y', size=(14))
plt.xlabel('x', size=(14))

but it didn't work. I have also tried other ways, like using plt.legend, but it didn't work.

My end goal: To change the legend to have labels based on the names of those observations (from column name)

Edit: I have tried:

plt.figure()
for i in range(df.shape[1]):
  plt.plot(df, df.iloc[3000:3005,:].loc[:,float_cols], label = df.columns['name'])

plt.legend()
plt.tight_layout()
plt.show()

but it didn't work got this error:

IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

also tried this:

plt.figure()
for i in range(df.shape[1]):
  plt.plot(df, df.iloc[3000:3005,:].loc[:,float_cols], label = df.columns[i])

plt.legend()
plt.tight_layout()
plt.show()

But also got error:

ValueError: x and y must have same first dimension, but have shapes (8606, 444) and (5, 438)

EDIT 2: Tried this:

targets = df['name']

plt.figure()
for i in range(df.shape[1]):
    plt.plot(df.iloc[3000:3005,:], label = targets[i])

plt.legend()
plt.tight_layout()
plt.show()

got the error:

in 3 plt.figure() 4 for i in range(df.shape1): ----> 5 plt.plot(df.iloc[3000:3005,:], label = targets[i]) 6 7 plt.legend()

~.conda\envs\reut\lib\site-packages\pandas\core\series.py in getitem(self, key) 869 key = com.apply_if_callable(key, self) 870 try: --> 871 result = self.index.get_value(self, key) 872 873 if not is_scalar(result):

~.conda\envs\reut\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key) 4403 k = self._convert_scalar_indexer(k, kind="getitem") 4404 try: -> 4405 return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None)) 4406 except KeyError as e1: 4407 if len(self) > 0 and (self.holds_integer() or self.is_boolean()):

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

Upvotes: 0

Views: 4156

Answers (1)

Liris
Liris

Reputation: 1511

Using matplotlib regular plt.plot():

import matplotlib.pyplot as plot
import pandas as pd
import numpy as np

x = np.linspace(0, 10, 100)

targets = ['cos(x)', 'sin(x)', 'cos(x) + sin(x)']
d = {'col1': np.cos(x), 'col2': np.sin(x), 'col3': np.sin(x) + np.cos(x)}
df = pd.DataFrame(data = d)

plt.figure()
for i in range(df.shape[1]):
  plt.plot(x, df.iloc[:,i], label = targets[i])

plt.legend()
plt.tight_layout()
plt.show()

enter image description here

You can change targets to what ever you want, including df['name'], depending on the organization of your dataframe.

Finally, if you don't have an x vector, just use plt.plot( df.iloc[:,i], label = targets[i]) instead, and it will plot your data with respect to position indices, as in your example in your question.

EDIT based on comments and discussion in chat:

For your case, you can try something similar to:

indexes_wanted = [2000, 100, 3200]
targets = df['names']

plt.figure()
for i in indexes_wanted:
  plt.plot(x, df.iloc[i, :][float_cols], label = targets.iloc[i])

plt.legend()
plt.tight_layout()
plt.show()

Upvotes: 1

Related Questions