如何使用Matplotlib在绘图中放置自定义图例符号? 为了在绘图中绘制自定义的图例符号,我们可以执行以下步骤- 设置图片大小和调整子图之间和周围的填充。 继承 HandlerPatch 类,覆盖create_artists方法,向图形添加椭圆形补丁,并返回补丁处理器。 使用 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], ["一个椭圆形,自定义图例元素"], handler_map={mpatches.Circle: HandlerEllipse()}) plt.show() PythonCopy 输出