3.Matplotlib設置legend圖例,設置標註

0 引言

Matplotlib繪圖完成後,有時候爲了更加完美,會在角落設置圖例,或者座標系中有時候需要標註來說明該曲線。

1 legend圖例

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. ]

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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章