gpt4 book ai didi

python - 使用 mpatches.Patch 自定义图例

转载 作者:行者123 更新时间:2023-12-03 21:27:05 25 4
gpt4 key购买 nike

我正在使用以下代码创建自定义 matplotlib 图例。

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
colors = ["g", "w"]
texts = ["Green Data Description", "RedData Description"]
patches = [ mpatches.Patch(color=colors[i], label="{:s}".format(texts[i]) ) for i in range(len(texts)) ]
plt.legend(handles=patches, bbox_to_anchor=(0.5, 0.5), loc='center', ncol=2 )

结果图例如下:

enter image description here

1 - 图例中的白色符号未显示,因为默认图例背景也是白色。如何将图例背景设置为其他颜色?

2 - 如何将图例中的矩形符号更改为圆形?

最佳答案

  • 可以使用 facecolor plt.legend() 参数设置图例的背景颜色,
     plt.legend(facecolor="plum")
  • 要获得圆形图例句柄,您可以使用带有圆形标记的标准绘图作为代理艺术家,
     plt.plot([],[], marker="o", ms=10, ls="")

  • 完整示例:
    import matplotlib.patches as mpatches
    import matplotlib.pyplot as plt
    colors = ["g", "w"]
    texts = ["Green Data Description", "RedData Description"]
    patches = [ plt.plot([],[], marker="o", ms=10, ls="", mec=None, color=colors[i],
    label="{:s}".format(texts[i]) )[0] for i in range(len(texts)) ]
    plt.legend(handles=patches, bbox_to_anchor=(0.5, 0.5),
    loc='center', ncol=2, facecolor="plum", numpoints=1 )

    plt.show()
    (请注意,只有旧版本的 matplotlib 才需要 mecnumpoints 参数)
    enter image description here
    对于图例中更复杂的形状,您可以使用自定义处理程序映射,请参阅 legend guide 或例如以 this answer 为例

    关于python - 使用 mpatches.Patch 自定义图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47307315/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com