Pandas 不更改图例标签

问题描述 投票:0回答:4

我正在尝试绘制我的数据,但是 pandas 使用我需要在图例中覆盖的列标签。我以为 label 关键字会改变这一点,但它似乎没有效果。谷歌搜索显示这是 0.15 版本中的一个错误,但我现在有 0.25。有谁知道解决这个问题的方法吗?

示例代码:

x = pd.DataFrame(list(range(2,513, 2)), columns=['x'])
y = pd.DataFrame(np.random.rand(256), columns=['y'])
df = pd.concat([x, y], axis=1)
df = df.set_index(['x'])
df.plot(label='Random')

我希望图例将“随机”列为曲线的标签。

python pandas
4个回答
2
投票

标签似乎是根据系列名称自动创建的。作为解决方法,您可以在绘图之前重命名您的

y
系列,即:

df.y.rename('Random').plot(legend=True)

0
投票

Pandas 绘图功能依赖于 matplotlib。您可以使用标准的 matplotlib 函数来设置标签、图例等

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

x = pd.DataFrame(list(range(2,513, 2)), columns=['x'])
y = pd.DataFrame(np.random.rand(256), columns=['y'])
df = pd.concat([x, y], axis=1)
df = df.set_index(['x'])
df.plot()
plt.legend(['Random'])
plt.show()

0
投票

几年前就讨论过这个问题这里

在您的情况下,您需要指定要在 y 轴上绘制的列

x = pd.DataFrame(list(range(2,513, 2)), columns=['x'])
y = pd.DataFrame(np.random.rand(256), columns=['y'])
df = pd.concat([x, y], axis=1)
df = df.set_index(['x'])
df.plot(y='y',label='Random')

0
投票

截至 2024 年,使用 pandas==2.0.3 和 matplotlib==3.5.2 这个问题仍然在 Pandas 中出现(它应该通过所有 kwargs),但前提是您将 .plot() 应用于 DataFrame(而不是比系列)。直接使用 matplotlib 时它可以按预期工作,并且如果您 .plot() 一个 Series,它也可以在 Pandas 中工作。

这里的示例用例是,我们有一个数据集,其中每个时间序列点都表示类别,因此我们希望在时间序列上为每个类别绘制线图,其中同一列每次表示 y 值,并根据类别。

想象一下您每天进行的分类(分组)测量,该测量返回类别、值和日期。假设列名称只是“CategorizedMetricValue” - 我们希望同一列的每个图的标签都不同,并根据不同的类别进行过滤。

Pandas DataFrame 图(标签未传递给图例):

# Plot each y-line (where category is x) in turn
for x in xList:
    thisColour = next(colourList)
    renderDataDF[renderDataDF[xColumn] == x][[yColumn]].plot(ax=thisAx, alpha=0.5, color=thisColour, label=x)
                                           

后续的

thisAx.legend()
只是多次重复y列名称。现在,我们可以简单地将 xList 提供给图例 (
thisAx.legend(xList)
),但 Matplotlib 文档建议不要这样做。

直接使用Matplotlib,一切正常,您将获得预期的图例条目:

thisAx.plot(renderDataDF[renderDataDF[xColumn] == x][[yColumn]], alpha=0.5, color=thisColour, label=x)

但是如果我们尝试使用原始的 Pandas .plot() 来使用一系列而不是 DataFrame,我们会发现图例会按预期填充

renderDataDF[renderDataDF[xColumn] == x][yColumn].plot(ax=thisAx, alpha=0.5, color=thisColour, label=x)
© www.soinside.com 2019 - 2024. All rights reserved.