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

编程入门 行业动态 更新时间:2024-10-28 08:29:50

plt.legend()画图例的<a href=https://www.elefans.com/category/jswz/34/1769370.html style=几种例子"/>

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

参考文档链接:/

1.Place the legend inside

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

import matplotlib.pyplot as plt
import numpy as npy = [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 npdef gamma(x):ans = 1#注意:不能用range(5),这样会从0开始,导致ans的值永远为0for i in range(1,x):ans = ans * ireturn ansdef 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 npy = [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()

更多推荐

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

本文发布于:2023-07-28 19:46:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1291664.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:几种   画图   例子   plt   legend

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!