Tuesday, 15 January 2013

python - Legend format lost after using: ax.legend(handles, labels ) -



python - Legend format lost after using: ax.legend(handles, labels ) -

i have same problem in post: user wants delete repeated entries in legend:

stop matplotlib repeating labels in legend

the reply works me well, however, when utilize it, legend format lost. happens when apply ax.legend(handles, labels) method. next code (copied http://matplotlib.org/examples/pylab_examples/legend_demo.html) illustrates issue:

# illustration info = np.arange(0,3, .02) b = np.arange(0,3, .02) c = np.exp(a) d = c[::-1] # create plots pre-defined labels. # alternatively, 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') # add together legend customizations. legend = ax.legend(loc='upper center', shadow=true) handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels ) # frame matplotlib.patches.rectangle instance surrounding legend. frame = legend.get_frame() frame.set_facecolor('0.90') # set fontsize label in legend.get_texts(): label.set_fontsize('large') label in legend.get_lines(): label.set_linewidth(1.5) # legend line width plt.show()

result without using 'ax.legend(handles, labels)':

resul using 'ax.legend(handles, labels)':

any advice welcomed

edit 1: typo 'without' corrected

you have issued legend() phone call twice , sec time 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 trick.

python matplotlib label legend handle

No comments:

Post a Comment