通过 matplotlib 中的列值更改图例条目

Change the legend enteries by column values in matplotlib

我在更改 matplotlib 图表图例中的标签时遇到了很多困难。 这是我的图表:

我想更改图例,以便标签将基于列名称中名为 "name" 的列中的值。

这是我创建原始图表的方式:

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))

这就是我尝试将图例更改为列名称的方式:

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))

但是没用。我也尝试过其他方法,比如使用 plt.legend,但没有用。

我的最终目标:根据这些观察的名称(来自列名称)更改图例以具有标签

编辑:我试过:

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()

但它没有工作得到这个错误:

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

也试过这个:

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()

但也有错误:

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

编辑 2:试过这个:

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()

得到错误:

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

使用matplotlib正则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()

您可以将 targets 更改为您想要的任何内容,包括 df['name'],具体取决于数据框的组织方式。

最后,如果您没有 x 向量,只需使用 plt.plot( df.iloc[:,i], label = targets[i]) 代替,它会根据位置索引绘制您的数据,如您问题中的示例所示。

根据聊天中的评论和讨论进行编辑:

对于您的情况,您可以尝试类似的操作:

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()