python - 是否可以通过多次绘图函数调用迭代地建立图例条目?

标签 python matplotlib legend

基于这里的问题和答案(Line plus shaded region for error band in matplotlib's legend 并且类似于 Combined legend entry for plot and fill_between)我能够创建一个结合了线和补丁元素的图例条目。

在我的用例中,我需要绘制其中的多个。当我这样做时,我只会得到最后一行 + 补丁组合的图例条目。

import numpy as np
import matplotlib.pyplot as plt

def plot(x, y, ax, col, group, **kwargs):
    hline, = ax.plot(x, y, 'k--', color=col)
    hpatch = ax.fill_between(x, y+10, y-10, color=col, alpha=0.5)
    ax.legend([(hline, hpatch)], [f"group {group}: Mean + interval"])

fig, ax = plt.subplots()
x = np.linspace(1, 100, 100)
plot(x, x, ax, "C0", 1)
plot(x, x+30, ax, "C1", 2)
plot(x, x+60, ax, "C2", 3)

enter image description here

请注意图例中仅存在最后一个(第 3 组)条目。

有没有办法让图例中包含所有线/路径组,以便(在这种情况下)图例中有 3 个项目?

如果这可以完全在 plot 函数中处理,则可以加分,避免必须从 plot 函数传递句柄。

这个问题不是问多个独立的图例。

最佳答案

对于图例中出现的内容,matplotlib 使用 label= 关键字。 您可以使用 ax.get_legend_handles_labels() 查找所有具有标签的元素。重新组合这些句柄和标签可以创建您想要的图例。多次调用 ax.legend 将清除旧图例并设置新图例。

测试代码将 ax.plot(x, y, 'k--', ... 替换为 ax.plot(x, y, '--', .. .。请注意,此处 k 会将线条涂成黑色,但颜色已由 color= 关键字设置。

import matplotlib.pyplot as plt
import numpy as np

def plot(x, y, ax, col, group, **kwargs):
    ax.plot(x, y, '--', color=col, label=f"group {group}: Mean")
    ax.fill_between(x, y + 10, y - 10, color=col, alpha=0.5, label='interval')
    handles, labels = ax.get_legend_handles_labels()
    print(handles, labels)
    ax.legend(handles=[(h1, h2) for h1, h2 in zip(handles[::2], handles[1::2])],
              labels=[l1 + " + " +l2 for l1, l2 in zip(labels[::2], labels[1::2])])

fig, ax = plt.subplots()
x = np.linspace(1, 100, 100)
plot(x, x, ax, "C0", 1)
plot(x, x + 30, ax, "C1", 2)
plot(x, x + 60, ax, "C2", 3)

plt.tight_layout()
plt.show()

plot with extending the legend

关于python - 是否可以通过多次绘图函数调用迭代地建立图例条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74930795/

相关文章:

python - 使用 python 和 Beautifulsoup4 从抓取数据中编写和保存 CSV 文件

python - 如何旋转矩形 cv2 python

python - matplotlib 分离散点图点并创建分割曲线

Python:同步程序中的Websockets

python - 在 OSX 上运行 django

fonts - Matplotlib 字体系列 : using Arno Pro or other fonts

python - matplotlib 复值函数图

从 ggplot2 中的图例中删除标签

r - 将图例添加到多个 for 循环图的边距

python - 如何修改图例中的文字排列