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

Posted

技术标签:

【中文标题】通过 matplotlib 中的列值更改图例条目【英文标题】:Change the legend enteries by column values in matplotlib 【发布时间】: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/… 【参考方案1】:

使用 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]),它会根据位置索引绘制您的数据,就像您问题中的示例一样。

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

对于您的情况,您可以尝试类似的方法:

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

【讨论】:

它不起作用,你可以在我的原始帖子中看到。我不知道为什么它不起作用,可能是因为它不是 x-y 但它有更多维度,所以标签不是列的名称,而是列中的值 现在图例标签是索引,我想从列“name”中获取值 您可能想要编辑您的初始帖子,因为“来自列名”具有误导性。 我现在编辑了,希望更清楚,如果你有什么想法我很想知道 如果解决方案现在令人满意,请考虑接受答案。

以上是关于通过 matplotlib 中的列值更改图例条目的主要内容,如果未能解决你的问题,请参考以下文章

Matplotlib 图例

如何在 matplotlib 中更改图例字体名称

更改图例标签时,Matplotlib 图例颜色会发生变化

For 循环中的 Matplotlib 图例

更改 bigquery 中的列值

确定熊猫数据框中的列值何时更改