将matplotlib图例markersize设置为常量

时间:2018-11-24 23:11:27

标签: python-3.x matplotlib legend

我正在使用matplotlib绘制图表,它具有plt.Circles和plt.axvlines来代表不同的形状。我需要一个图例来描述这些形状,但是问题是图例标记(图像部分)根据输入改变了大小,这看起来很糟糕。如何将尺寸设置为常数?

fig = plt.figure(figsize=(6.4, 6), dpi=200, frameon=False)
ax = fig.gca()
# 3 Circles, they produce different sized legend markers
ax.add_patch(plt.Circle((0,0), radius=1, alpha=0.9, zorder=0, label="Circle"))
ax.add_patch(plt.Circle((-1,0), radius=0.05, color="y", label="Point on Circle"))
ax.add_patch(plt.Circle((1, 0), radius=0.05, color="k", label="Opposite Point on Circle"))
# A vertical line which produces a huge legend marker
ax.axvline(0, ymin=0.5-0.313, ymax=0.5+0.313, linewidth=12, zorder=1, c="g", label="Vertical Line")
ax.legend(loc=2)
ax.set_xlim(-2,1.2) # The figsize and limits are meant to preserve the circle's shape
ax.set_ylim(-1.5, 1.5)
fig.show()

我见过解决方案,包括legend.legendHandles [0] ._ size或各种分类,无论我设置的值如何,它似乎都不会改变

1 个答案:

答案 0 :(得分:1)

圆的图例标记的大小不同,因为第一个圆没有边缘颜色,而其他两个圆具有通过color设置的边缘颜色。您可以设置圆形的面色。另外,您可以将所有3个圆的线宽设置为相等。

该行的图例标记是如此之大,因为它只是从绘图中的该行复制属性。如果要使用其他线宽,可以通过相应的图例处理程序对其进行更新。

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D

def update_prop(handle, orig):
    handle.update_from(orig)
    handle.set_linewidth(2)

fig, ax = plt.subplots(figsize=(6.4, 6), dpi=200, frameon=False)

# 3 Circles, set the facecolor instead of edge- and face-color
ax.add_patch(plt.Circle((0,0), radius=1, alpha=0.9, zorder=0, label="Circle"))
ax.add_patch(plt.Circle((-1,0), radius=0.05, facecolor="y", label="Point on Circle"))
ax.add_patch(plt.Circle((1, 0), radius=0.05, facecolor="k", label="Opposite Point on Circle"))

# Line, update the linewidth via 
ax.axvline(0, ymin=0.5-0.313, ymax=0.5+0.313, linewidth=12, zorder=1, c="g", label="Vertical Line")
ax.legend(loc=2, handler_map={plt.Line2D:HandlerLine2D(update_func=update_prop)})


ax.set_xlim(-2,1.2)
ax.set_ylim(-1.5, 1.5)
plt.show()

enter image description here