Python学习笔记(八)-(2)matplotlib作图之legend

1. handles和labels


legend(*args, **kwargs) :

(1)*args为可选参数,为了确定legend必须的两个对象:handles和labels。其中,handles是被标示的对象,labels是标示内容。
(2)**kwargs是其他选项。

代码:
#--------coding=GBK------------
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3*np.pi,3*np.pi,100)
y,z = np.sin(x)/x,-np.sin(x)/x
m,n = 1/(1+np.exp(-x)),np.tanh(x)
# help(plt.legend)

#----------------------handles和labels----------------------------#
plt.figure()
Yplot = plt.plot(x,y,"r",label='sin(x)/x',linestyle='--')  # 2D图
print(plt.gca())
handles, labels = plt.gca().get_legend_handles_labels() # 自动获取handles和labels
print(handles==Yplot)   # 一个图的时候才相等
print('handles = ',handles,'\n','labels = ',labels,'\n')  # handle是图形对象,label是字符串
print(type(handles),type(labels))  # handles和labels都是list,这样的话顺序什么的都好调,甚至删除、增加都是可以的
plt.legend(handles,labels) # 调用legend()函数
plt.savefig('1.jpg')
输出:
AxesSubplot(0.125,0.11;0.775x0.77)
True
handles =  [<matplotlib.lines.Line2D object at 0x000000000EA07588>] 
 labels =  ['sin(x)/x'] 

<class 'list'> <class 'list'>

1.jpg:


2. 单个legend

代码:

#---------------------------单个legend--------------------------#
#-------------方法一-------------#
plt.figure()   
plt.subplot(1,2,1) 
Z1plot, = plt.plot(x,z,"b",label='sin(x)/x',linestyle='-.')  # 逗号必须有
plt.legend()        # 默认用get_legend_handles_labels获取handles和labels

#-------------方法二-------------#
plt.subplot(1,2,2)    
Z2plot, = plt.plot(x,z,"b",linestyle='-.')  
plt.legend(handles = [Z2plot],labels = ['LaLa']) # 自己给出handles和labels
plt.savefig('2.jpg') 

2.jpg:


3.多个legend

代码:

#---------------------------多个legend--------------------------#
#------------方法一----------# 
plt.figure() 
plt.subplot(1,3,1)
Mplot, = plt.plot(x,m,"c",label='sigmoid',linewidth=2) 
Nplot, = plt.plot(x,n,"m",label='tanh')
Mlegend = plt.legend(handles=[Mplot],loc=2) # 先创建一个artist
plt.gca().add_artist(Mlegend)  # 再添加一个artist
plt.legend(handles=[Nplot],loc=4) # 位置默认是重合的,所以需要用loc设置一下

#------------方法二----------#
plt.subplot(1,3,2)
Oplot, = plt.plot(x,m,"k.") 
Pplot, = plt.plot(x,n,"y")
plt.legend(handles=[Pplot,Oplot],labels=['tanh','sigmoid'])  # 给出handles和labels,注意可以换顺序

#------------方法三----------#
plt.subplot(1,3,3)
plt.plot(x,m,"y",label='sigmoid',linewidth=1) 
plt.plot(x,n,"g",label='tanh')
plt.legend() # 直接用默认的
plt.savefig('3.jpg') 

3.jpg:


4.legend位置


代码:

#---------------------------legend的位置--------------------------#
plt.figure()
def Draw(i):
    plt.subplot(3,3,i)
    plt.legend(handles = Yplot,labels=str(i),loc=i)
for i in range(1,10):
    Draw(i)
plt.savefig('4.jpg')
4.jpg:

5.legend样式

待续。。。

6.总结

  • 理解和会用handles和labels是关键

7.参考

参考: matplotlib官网

版权声明:本文为博主原创文章,未经博主允许不得转载。


发布了14 篇原创文章 · 获赞 19 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_24694761/article/details/79176789