Matplotlib绘图完成后,有时候为了更加完美,会在角落设置图例,或者坐标系中有时候需要标注来说明该曲线。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,100)
y1 = 2*x +1
y2 = x**2
# xy范围
plt.xlim(-1,2)
plt.ylim(-2,3)
# xy描述
plt.xlabel('I am X')
plt.ylabel('I am Y')
# 设置l1和l2,并传入到 .legend图例中
l1, = plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
l2, = plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')
plt.legend(handles=[l1,l2],labels=['test1','test2'],loc='best')
new_ticks = np.linspace(-2,2,11)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-1,0,1,2,3],
['level1','level2','level3','level4','level5'])
plt.show()
[-2. -1.6 -1.2 -0.8 -0.4 0. 0.4 0.8 1.2 1.6 2. ]
主要通过 plt.annotate来设置曲线的标注,调用 plt.text来设置文本标注。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,100)
y1 = 2*x +1
y2 = x**2
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='-')
# gca get current axis
ax = plt.gca()
# 把右边和上边的边框去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 把x轴的刻度设置为‘bottom'
# 把y轴的刻度设置为 ’left‘
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 设置bottom对应到0点
# 设置left对应到0点
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
x0 = 0.5
y0 =2*x0 + 1
# 画点
plt.scatter(x0,y0,s=50,color='b')
# 画虚线
plt.plot([x0,x0],[y0,0],'k--', lw=2)
plt.annotate(r'$2x+1=%s$' % y0,xy=(x0,y0),xytext=(+30,-30),textcoords='offset points',fontsize=16,
arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
plt.text(-1,2,r'$this\ is\ the\ text$',fontdict={
'size':'16','color':'r'})
plt.show()