【发布时间】:2020-06-21 04:05:00
【问题描述】:
我在更改 matplotlib 图表中图例中的标签时遇到了很多困难。 这是我的图表:
我想更改图例,以便标签将基于列名称中名为“名称”的列中的值。
这就是我创建原始图表的方式:
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: 只有整数、切片 (
:)、省略号 (...)、 numpy.newaxis (None) 和整数或布尔数组是有效的索引
也试过这个:
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 和 y 必须具有相同的第一维,但具有形状 (8606, 444) 和 (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()
得到错误:
在 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 在 getitem(自我,钥匙) 第869章 870尝试: --> 871 结果 = self.index.get_value(self, key) 872 873 如果不是 is_scalar(结果):
~.conda\envs\reut\lib\site-packages\pandas\core\indexes\base.py 在 get_value(自我,系列,键)4403 k = self._convert_scalar_indexer(k, kind="getitem") 4404 尝试: -> 4405 return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None)) 4406 除了 KeyError as e1: 4407 if len(self) > 0 and (self.holds_integer() 或 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 在 pandas._libs.hashtable.Int64HashTable.get_item()
pandas_libs\hashtable_class_helper.pxi 在 pandas._libs.hashtable.Int64HashTable.get_item()
密钥错误:0
【问题讨论】:
-
您可以使用常规 matplolib
plt.plot()循环列,修改此示例:matplotlib.org/gallery/text_labels_and_annotations/…
标签: python matplotlib label legend