Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

python - Matplotlib Legend Guide basic examples

I am trying to understand how to use the legend() better, specifically how to use proxy artists. I find the Legend guide to be severely lacking. This post is somewhat similar to this one.

I am using Python 2.7.5 on Windows 7, matplotlib version 1.2.1. I wrote this code which is essentially a combination of the examples in the legend guide:

import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')

blue_line = mlines.Line2D([], [], color='blue', marker='*',
                      markersize=15, label='Blue stars')
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend([red_patch,blue_line])

plt.show()

http://i.stack.imgur.com/E9jkA.jpg

The legend label colors are not those assigned in the handles, nor are they a patch and a line with stars. I have tried removing and adding the lines, adding and removing the commas after the lines, etc. Are they any better references for using legend()? Any other tips for using proxy artists? I don't understand why the examples give me totally different results...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Legend Guide was rewritten to be compatible with matplotlib version 1.4.0 or newer. Your version of matplotlib (1.2.1) is over two years old. Don't be surprised if everything shown in the docs does not work with such an old version.

If you upgrade your version, then using

plt.legend(handles=[red_patch,blue_line])

(as is shown in the Legend Guide) instead of

plt.legend([red_patch,blue_line])

yields

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...