0

I have the same problem as in this post: Where the user wants to delete repeated entries in the legend:

Stop matplotlib repeating labels in legend

The answer works for me as well, however, when I use it, the legend format is completely lost. This happens when I apply the ax.legend(handles, labels) method. The following code (copied from http://matplotlib.org/examples/pylab_examples/legend_demo.html) illustrates this issue:

# 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()

Result without using 'ax.legend(handles, labels)': enter image description here

Resul using 'ax.legend(handles, labels)': enter image description here

Any advice would be most welcomed

EDIT 1: Typo 'without' corrected

Community
  • 1
  • 1
Delosari
  • 677
  • 2
  • 17
  • 29

1 Answers1

3

You have issued legend() call twice and the second time it is called without formatting arguments, replace:

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

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

with

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)

Should do the trick.

CT Zhu
  • 52,648
  • 17
  • 120
  • 133