使用后传奇格式丢失:ax.legend(句柄,标签)

时间:2014-06-20 00:11:11

标签: python matplotlib label legend handle

我遇到与此帖相同的问题:用户想要删除图例中的重复条目:

Stop matplotlib repeating labels in legend

答案也适用于我,但是,当我使用它时,图例格式完全丢失了。当我应用ax.legend(handle,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(句柄,标签)': enter image description here

Resul使用' ax.legend(句柄,标签)': enter image description here

欢迎任何建议

编辑1:错字'没有'校正

1 个答案:

答案 0 :(得分: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)

应该做的伎俩。