2014-02-25 77 views
1

如何将图例添加到Matylotlib中的IPython笔记本内的xy线图?我目前的尝试:Matplotlib xy线图图例

x = np.linspace(0, 3*np.pi, 500) 
a = plt.plot(x, np.sin(x**2)) 
b = plt.plot(x, np.sin(x**0.5)) 
plt.legend([a,b], ['square', 'square root']) 

这样做,我得到以下错误:

/Users/mc/.virtualenvs/kaggle/lib/python2.7/site-packages/matplotlib/legend.py:613: UserWarning: Legend does not support [] Use proxy artist instead.

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist

(str(orig_handle),)) /Users/mc/.virtualenvs/kaggle/lib/python2.7/site-packages/matplotlib/legend.py:613: UserWarning: Legend does not support [] Use proxy artist instead.

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist

(str(orig_handle),))

此命令的作用,如果我做plt.scatter代替plt.plot,但我想了曲线图,而不是X,Y点。

回答

2

这样做怎么样?

x = np.linspace(0, 3*np.pi, 500) 
fig, ax = plt.subplots() 
a = ax.plot(x, np.sin(x**2), label = 'square') 
b = ax.plot(x, np.sin(x**0.5), label = 'square root') 
handles, labels = ax.get_legend_handles_labels() 
ax.legend(handles, labels) 

为了得到这个:

enter image description here