matplotlib plt.lengend图例放在图像的外侧

参考:https://www.jb51.net/article/186659.htm

 

matplotlib plt.lengend图例放在图像的外侧

 

1、图例在图中实例


import numpy as np
import matplotlib.pyplot as plt

# 定义x,y
X = np.linspace(0, 2*np.pi, 32, endpoint=True)
C = np.cos(X)

# figure的名称
plt.figure('demon plot')
# 画图
plt.plot(X, C, 'r--', label = 'cos')

# 显示x、y坐标代表的含义
plt.xlabel('Independent variable x')
plt.ylabel('dependent variable y')

# 显示图的标题
plt.title(' demo')

# 显示图例
# ------在图中右下角-------------
'''
loc的可选参数
0: 'best'
1: 'upper right'
2: 'upper left'
3: 'lower left'    
4: 'lower right'
5: 'right'
6: 'center left'   
7: 'center right'
8: 'lower center'
9: 'upper center'
10: 'center'
'''
plt.legend(loc='lower right')

plt.show()

运行结果:

 

2、图例在图外

plt.legend(bbox_to_anchor=(num1, num2), loc=num3, borderaxespad=num4)

说明:bbox_to_anchor被赋予的二元组中,num1用于控制legend的左右移动,值越大越向右边移动,num2用于控制legend的上下移动,值越大,越向上移动。用于微调图例的位置。

num1表示水平位置,num2表示垂直位置。

 

1)num1=0表示legend位于图像的左侧垂直线(其它设置:num2=0,num3=3,num4=0)

import numpy as np
import matplotlib.pyplot as plt

# 定义x,y
X = np.linspace(0, 2*np.pi, 32, endpoint=True)
C = np.cos(X)

# figure的名称
plt.figure('demon plot')
# 画图
plt.plot(X, C, 'r--', label = 'cos')

# 显示x、y坐标代表的含义
plt.xlabel('Independent variable x')
plt.ylabel('dependent variable y')

# 显示图的标题
plt.title(' demo')

# 显示图例

num1 = 0
num2 = 0
num3 = 3
num4 = 0
plt.legend(bbox_to_anchor=(num1, num2), loc=num3, borderaxespad=num4)

plt.show()

运行结果:

 

2num1=1表示legend位于图像的右侧垂直线(其它设置:num2=0,num3=3,num4=0)

运行结果:

 

 

3)为了美观,需要将legend放于图像的外侧,而又距离不是太大,一般设num1=1.01

运行结果:

 

4num2=0表示legend位于图像下侧水平线(其它设置num1=1.05,num3=3,num4=0)

运行结果:

 

5num2=1表示legend位于图像上侧水平线(其它设置:num1=1.05,num3=3,num4=0)

运行结果:

 

                                                                                  

 

  • 32
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值