Python 为自定义图例使用mpatches.Patch
我正在使用以下代码创建自定义matplotlib图例Python 为自定义图例使用mpatches.Patch,python,matplotlib,legend,Python,Matplotlib,Legend,我正在使用以下代码创建自定义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]) )
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-图例中的白色符号不显示,因为默认图例背景也是白色的。如何将图例背景设置为其他颜色
2-如何将图例中的矩形符号更改为圆形?尝试以下操作:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerPatch
colors = ["g", "w"]
texts = ["Green Data Description", "RedData Description"]
class HandlerEllipse(HandlerPatch):
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
p = mpatches.Ellipse(xy=center, width=width + xdescent,
height=height + ydescent)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
c = [ mpatches.Circle((0.5, 0.5), 1, facecolor=colors[i], linewidth=3) for i in range(len(texts))]
plt.legend(c,texts,bbox_to_anchor=(0.5, 0.5), loc='center', ncol=2, handler_map={mpatches.Circle: HandlerEllipse()}).get_frame().set_facecolor('#00FFCC')
plt.show()
输出:
更新:
要圆,请将宽度设置为高度,单位为mpatches.eliple
移除外部黑线,在mpatches中设置edgecolor=“none”
。圆圈
代码:
新图片:
facecolor
参数设置图例的背景色
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()
(请注意,mec
和numpoints
参数仅适用于较旧版本的matplotlib)
对于图例中更复杂的形状,您可以使用自定义处理程序映射,请参见或,例如,作为示例Thant正是我所需要的。非常感谢。但是如何编辑椭圆尺寸使其成为一个圆呢?如何去除其外部黑色轮廓?
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()