matplotlib图例设置

图例

  1. 设置 label,再使用 plt.legend()

    plt.plot(x,y1,label='y1')
    plt.plot(x,y2,color='red',linewidth=2.0,linestyle='--',label='y2')
    plt.legend()    #使用默认参数
    

在这里插入图片描述

  1. legend(*handles, *labels,loc) 参数设置

    plt.figure(num=4)  # figure对象名称、尺寸设置
    
    L1, = plt.plot(x,y1,label='y1')  #L1后面必须有逗号
    L2, = plt.plot(x,y2,color='red',linewidth=2.0,linestyle='--',label='y2') #L2后面必须有逗号
    
    plt.legend(handles=[L1,L2],labels=['aaa','bbb'],loc='upper left')
    

在这里插入图片描述

  • handles 所要处理的线,参数为列表

  • labels 所要处理的线的图例名称,参数为列表,名称对应 handles 相应位置

  • loc 表示图例位置, best 表示自动找一个比较合适的地方(不会覆盖住数据)放置

    loc常用参数:

    	best   			自动寻找合适位置
    	upper right		右上角
    	upper left		左上角
    	lower left		左下角
    	lower right		右下角
    	right			右边中间位置 =center right
    	center left		右边中间位置
    	center right	右边中间位置 
    	lower center	底部中间位置 
    	upper center	顶部中间位置 
    	center			整张图中间位置
    

完整代码:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-4, 4, 0.1)
y1 = np.cos(x) 
y2 = np.sin(x)

L1, = plt.plot(x, y1, color= 'r',label='y1')
L2, = plt.plot(x, y2, color= 'skyblue', label='y2')
plt.legend(handles=[L1,L2], labels=['aaa','bbb'],loc='lower left')
plt.show()
posted @ 2020-07-23 21:52  aJream  阅读(90)  评论(0编辑  收藏  举报