使用mpatches.Patch获得自定义图例 [英] using mpatches.Patch for a custom legend
问题描述
我正在使用以下代码创建自定义的matplotlib图例.
I'm using the following code to create a custom matplotlib legend.
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 )
结果图例如下:
1-图例中的白色符号未显示,因为默认图例背景也为白色.如何将图例背景设置为其他颜色?
1 - The white symbol in the legend is not shown because that the default legend background is white as well. How can I set the legend background to other color ?
2-如何将图例中的矩形符号更改为圆形?
2 - How to change the rectangular symbols in the legend into circular shape ?
推荐答案
-
要获取圆形图例手柄,您可以使用带有圆形标记的标准绘图作为代理艺术家
To obtain a circular shaped legend handle, you may use a standard plot with a circular marker as proxy artist,
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才需要mec
和numpoints
自变量)
(Note that mec
and numpoints
arguments are only required for older versions of matplotlib)
有关图例中更复杂的形状,可以使用自定义处理程序映射,请参见图例指南或例如此答案作为示例
For more complicated shapes in the legend, you may use a custom handler map, see the legend guide or e.g. this answer as an example
这篇关于使用mpatches.Patch获得自定义图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!