如何使用 Matplotlib 在图表中放置自定义图例符号?
要在一个图表中绘制自定义图例符号,我们可以采取以下步骤 −
- 设置图的大小并调整子图之间和周围的填充。
- 继承HandlerPatch 类,重写创建艺术家的方法,在图表中添加一个椭圆形贴片,并返回贴片处理程序。
- 使用Circle 类在图表上绘制一个圆。
- 在当前轴上添加一个圆贴片。
- 使用legend() 方法将图例放置在图表上。
- 使用show() 方法显示图形。
示例
import matplotlib.pyplot as plt, matplotlib.patches as mpatches from matplotlib.legend_handler import HandlerPatch plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True 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), 0.25, facecolor="green", edgecolor="red", linewidth=1) plt.gca().add_patch(c) plt.legend([c], ["An ellipse,Customized legend element"], handler_map={mpatches.Circle: HandlerEllipse()}) plt.show()
输出
广告