python - 让图例对应于 Pandas/PyPlot 中的 y 值

标签 python matplotlib pandas legend legend-properties

我有一个名为“original_filtered_df”的数据框。我正在尝试为两列(“COLOR”、“SIZE”)和另外两列(“WEIGHT”、“HEIGHT”)随时间(“DATE”)绘制每对可能的值。

下面的代码绘制正确。它创建了多个图,每个图对应一个可能的值(“COLOR”、“SIZE”)。每个图包含两行,一行用于“WEIGHT”,另一行用于“HEIGHT”。然而,图例名称并没有说“WEIGHT”或“HEIGHT”。他们都说“DATE”(x 轴)。如何强制图例引用 y 轴数据,以便名称显示“WEIGHT”和“HEIGHT”?

import matplotlib.pyplot as plt

for combo in original_filtered_df.groupby(['COLOR', 'SIZE'], as_index=True):
    color = combo[0][0]
    size = combo[0][1]
    filtered_df = original_filtered_df[(original_filtered_df["COLOR"] == color) & (original_filtered_df["SIZE"] == size)]
    plt.figure()
    filtered_df.plot(x="DATE", y="WEIGHT", color=(1,0,0))
    filtered_df.plot(x="DATE", y="HEIGHT", color=(0,1,0))

    #patches, labels = ax.get_legend_handles_labels()
    #ax.legend(patches, labels, loc='center left', bbox_to_anchor=(1, 0.5))

    plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.title("COLOR " + str(color) + ", SIZE " + size)

最佳答案

我不确定为什么图例的标签默认为 x 轴,但我在绘图时通过执行以下操作解决了这个问题:

filtered_df.plot(x="DATE", y="WEIGHT", color=(1,0,0), label="WEIGHT")
filtered_df.plot(x="DATE", y="HEIGHT", color=(0,1,0), label="HEIGHT")

有了这个,图例函数使用了正确的 y 轴标签。

关于python - 让图例对应于 Pandas/PyPlot 中的 y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28682004/

相关文章:

Python - 用匹配的对值替换正则表达式匹配

python - 根据不同的表有效地复制数据帧行

python - 如何使用 Matplotlib 从灰度图像创建曲面图?

python + matplotlib : barh plot show incomplete YTick labels - how to dynamically move the plot area to the right to fit the given YTickLabels?

python - intersphinx 链接到 pandas autodoc API

Python用户定义的模块在哪里导入系统模块

python - 将 matplotlib 动画保存为 mp4

python - Python 处理重复项

python - Pandas DataFrame 中列的值列表

python skimage.measure.label 在linux环境下导致segment fault