plt.annotate()函數用於標注文字
plt.annotate(s,sy,*args,**kwargs)
參數解釋:
-
s 為注釋文本內容
-
xy 為被注釋的坐標點
-
xytext 為注釋文字的坐標位置
-
xycoords 參數如下:
- figure points:圖左下角的點
- figure pixels:圖左下角的像素
- figure fraction:圖的左下部分
- axes points:坐標軸左下角的點
- axes pixels:坐標軸左下角的像素
- axes fraction:左下軸的分數
- data:使用被注釋對象的坐標系統(默認)
- polar(theta,r):if not native ‘data’ coordinates t
-
weight 設置字體線型
- {‘ultralight’, ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’}
-
color 設置字體顏色
- {‘b’, ‘g’, ‘r’, ‘c’, ‘m’, ‘y’, ‘k’, ‘w’}
- ‘black’,'red’等
- [0,1]之間的浮點型數據
- RGB或者RGBA, 如: (0.1, 0.2, 0.5)、(0.1, 0.2, 0.5, 0.3)等
-
arrowprops #箭頭參數,參數類型為字典dict
- width:箭頭的寬度(以點為單位)
- headwidth:箭頭底部以點為單位的寬度
- headlength:箭頭的長度(以點為單位)
- shrink:總長度的一部分,從兩端“收縮”
- facecolor:箭頭顏色
-
bbox給標題增加外框 ,常用參數如下:
- boxstyle:方框外形
- facecolor:(簡寫fc)背景顏色
- edgecolor:(簡寫ec)邊框線條顏色
- edgewidth:邊框線條大小
例子:
import matplotlib.pyplot as plt import numpy as np x = np.arange(0, 6) y = x * x plt.plot(x, y, marker='o') for xy in zip(x, y): plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points') plt.show()
weight參數
plt.plot(x, y, marker='o') for xy in zip(x, y): plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points', weight='heavy') plt.show()
把arrowprops參數改成通過dict傳入參數(facecolor = “r”, headlength = 10, headwidth = 30, width = 20)
plt.plot(x, y, marker='o') for xy in zip(x, y): plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points', arrowprops = dict(facecolor = "r", headlength = 10, headwidth = 30, width = 20)) plt.show()
把bbox參數改成通過dict傳入參數(boxstyle=‘round,pad=0.5’, fc=‘yellow’, ec=‘k’,lw=1 ,alpha=0.5)
plt.plot(x, y, marker='o') for xy in zip(x, y): plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points', bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k', lw=1, alpha=0.5)) plt.show()
arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red')
### 可視化預測新樣本 plt.figure() ## new point 1 x_fearures_new1 = np.array([[0, -1]]) plt.scatter(x_fearures_new1[:,0],x_fearures_new1[:,1], s=50, cmap='viridis') plt.annotate(s='New point 1',xy=(0,-1),xytext=(-2,0),color='blue',arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red')) ## new point 2 x_fearures_new2 = np.array([[1, 2]]) plt.scatter(x_fearures_new2[:,0],x_fearures_new2[:,1], s=50, cmap='viridis') plt.annotate(s='New point 2',xy=(1,2),xytext=(-1.5,2.5),color='red',arrowprops=dict(arrowstyle='-|>',connectionstyle='arc3',color='red')) ## 訓練樣本 plt.scatter(x_fearures[:,0],x_fearures[:,1], c=y_label, s=50, cmap='viridis') plt.title('Dataset') # 可視化決策邊界 plt.contour(x_grid, y_grid, z_proba, [0.5], linewidths=2., colors='blue') plt.show()