参考文档链接: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()