使用 ax.legend(handles, labels ) 后图例格式丢失

0 投票
1 回答
1747 浏览
提问于 2025-04-18 10:26

我遇到的问题和这个帖子里的一样:用户想要删除图例中重复的条目。

停止matplotlib在图例中重复标签

这个答案对我也有效,不过,当我使用它的时候,图例的格式完全丢失了。这种情况发生在我使用ax.legend(handles, labels)这个方法时。下面的代码(从http://matplotlib.org/examples/pylab_examples/legend_demo.html复制过来的)展示了这个问题:

# Example data
a = np.arange(0,3, .02)
b = np.arange(0,3, .02)
c = np.exp(a)
d = c[::-1]

# Create plots with pre-defined labels.
# Alternatively, you can pass labels explicitly when calling `legend`.
fig, ax = plt.subplots()
ax.plot(a, c, 'k--', label='Model length')
ax.plot(a, d, 'k:', label='Data length')
ax.plot(a, c+d, 'k', label='Total message length')

# Now add the legend with some customizations.
legend = ax.legend(loc='upper center', shadow=True)

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels )   

# The frame is matplotlib.patches.Rectangle instance surrounding the legend.
frame = legend.get_frame()
frame.set_facecolor('0.90')

# Set the fontsize
for label in legend.get_texts():
    label.set_fontsize('large')

for label in legend.get_lines():
    label.set_linewidth(1.5)  # the legend line width
plt.show()

不使用'ax.legend(handles, labels)'的结果:

这里输入图片描述

使用'ax.legend(handles, labels)'的结果:

这里输入图片描述

任何建议都非常欢迎

编辑 1:修正了'typo'中的'without'

1 个回答

3

你调用了两次 legend() 这个函数,而第二次调用的时候没有传入格式化的参数。你需要把:

legend = ax.legend(loc='upper center', shadow=True)

handles, labels = ax.get_legend_handles_labels()
ax.legend(handles, labels )

换成

handles, labels = ax.get_legend_handles_labels()
by_label = OrderedDict(zip(labels, handles))
ax.legend(by_label.values(), by_label.keys(), loc='upper center', shadow=True)

这样就可以解决问题了。

撰写回答