使用Matplotlib绘制分组数据的图表

3
我使用Matplotlib和Pandas来绘制按z分组的x与y的图表。因此,我有以下内容:
x = df['ColumnA']
y = df['ColumnB']
fig, ax = plt.subplots(figsize=(20, 10))
for key, grp in df.groupby(['ColumnC']):
    plt.plot(grp['ColumnA'], grp['ColumnB'].rolling(window=30).mean(), label=key)

我也想强调将绘制的所有值中的两个特定值。
ax.legend(('Value1', 'Value2'))
plt.show()

这个很好用。我的图例中只有两个值,但实际上所有的值都被绘制了出来。我想要的是能够指定上述 2 个值的颜色,例如红色和蓝色,并将来自 C 列的所有其他值显示为一个颜色。目标是突出显示 Value 1 和 2 相对于其他所有值的表现。
1个回答

0

首先,更改感兴趣的线条的颜色。

lines_to_highlight = {
    'Value1': 'red',
    'Value2': 'blue'
}
DEFAULT_COLOR = 'gray'

legend_entries = []  # Lines to show in legend

for line in ax.lines:
    if line.get_label() in lines_to_highlight:
        line.set_color(lines_to_highlight[line.get_label()])

        legend_entries.append(line)
    else:
        line.set_color(DEFAULT_COLOR)

其次,创建您的图例。

ax.legend(
    legend_entries, 
    [entry.get_label() for entry in legend_entries]
)

注意事项:

  • ax.legend(('Value1', 'Value2')) 并不会像你期望的那样工作。它只是重置了你绘制的前两条线的标签,而不是限制图例只显示这些标签所对应的线条。(matplotlib文档本身也说这个错误很容易犯。)
  • 在设置线条颜色之后,必须调用 ax.legend(...)。否则,图例中的颜色可能与图中的颜色不匹配。

例子

import matplotlib.pyplot as plt

ax = plt.subplot(111)
ax.plot([1, 1, 1], label='one')
ax.plot([2, 2, 2], label='two')
ax.plot([3, 3, 3], label='three')

lines_to_highlight = {
    'one': 'red',
    'three': 'blue'
}
DEFAULT_COLOR = 'gray'

legend_entries = []  # Lines to show in legend

for line in ax.lines:
    if line.get_label() in lines_to_highlight:
        line.set_color(lines_to_highlight[line.get_label()])

        legend_entries.append(line)
    else:
        line.set_color(DEFAULT_COLOR)

ax.legend(
    legend_entries, [entry.get_label() for entry in legend_entries]
)
plt.show()

Minimal example


它接近了,但还不够。现在图例中的2个值已设置为红色和蓝色。但实际绘图中的所有内容都是灰色的。我只想让与图例中的值对应的2条线条被着色。 - Mark
1
感谢您的评价,@ Mark!我制作了一个示例并学习到 ax.legend(('Value1','Value2')) 的行为不是我们所期望的,并且错误的线条被标记。您可能需要在代码中进行调整。 不过,我不确定这是否是导致整个图形变灰的原因。也许尝试对要突出显示的线条使用 ax.plot(...,zorder = 2),对于不关心的线条使用 zorder = 1 - Emerson Harkin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接