- 图例的简单生成
- 方法1:使用变量存储函数,注意逗号的应用
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2,2,100)
y1 = 2*x + 1
y2 = x**2
ax = plt.gca()
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
p1, = plt.plot(x,y1)
p2, = plt.plot(x,y2)
plt.legend(handles = [p1,p2],labels = ['2x+1','x^2'],loc = 'best')
plt.show()
其中legend的loc参数可以有这么几个选择:
‘best’,‘upper right’,‘upper left’,‘lower right’,‘lower left’,‘right’,‘center left’,‘center right’,‘lower center’,‘upper center’
- 方法2: 使用plot时自带label属性,然后再用legend改变位置
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2,2,100)
y1 = 2*x + 1
y2 = x**2
ax = plt.gca()
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
plt.plot(x,y1,label = '2x+1')
plt.plot(x,y2,label = 'x^2')
plt.legend(loc = 'best')
plt.show()
- 简单的注释
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,100)
y1 = 2*x + 1
ax = plt.gca()
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
plt.plot(x,y1,color = 'red')
x0 = 0.5
y0 = 2*x0 +1
plt.scatter(x0,y0, s = 50,color = 'k')
plt.plot([x0,x0],[y0,0],'k--')
plt.annotate('zhushi',xy = (x0,y0),xytext = (1.5,0.5),color = 'k',arrowprops = dict(width = 2, color = 'purple',shrink = 0.05))
'''
xy=(横坐标,纵坐标) 箭头尖端
xytext=(横坐标,纵坐标) 文字的坐标,指的是最左边的坐标
arrowprops= dict(
color= '颜色',
shrink = '数字' <1 收缩箭头
width = 2,
)
'''
plt.show()