plt.legend()画图例的几种例子

参考文档链接:https://pythonspot.com/matplotlib-legend/

1.Place the legend inside

To place the legend inside, simply call legend():

import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend()
plt.show()

在这里插入图片描述

plt.legend()的参数loc与bbox_to_anchor

  • loc的取值:best/ upper right / upper left/ lower right / lower left/ center right / center left/ lower center / lower center/ center
  • bbox_to_anchor是box的定位坐标

2.Place the legend on bottom

import matplotlib.pyplot as plt
import numpy as np

def gamma(x):
    ans = 1
    #注意:不能用range(5),这样会从0开始,导致ans的值永远为0
    for i in range(1,x):
        ans = ans * i
    return ans

def beta(x, m, n):
    return (gamma(m+n) / (gamma(m) * gamma(n))) * x**(m-1) * (1-x)**(n-1)

x = np.linspace(0, 1, 1000)

y = beta(x, 2, 3)
plt.plot(x, y, label="Beta(2,3)")
plt.legend(loc="lower center")
plt.title('Beta(2,3)')
plt.show()

在这里插入图片描述

画多张子图

fig = plt.figure()
axis = plot.subplot(111) #1行1列,当前是第1个

3.Place the legend outside

chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)

Code:

import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend outside')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)
plt.show()

在这里插入图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值