Annotation標注
主要解決如何在圖像中添加注解
添加點和垂直線
#添加(x0,y0),大小為50,顏色為red
plt.scatter(x0,y0,s=50,color='r')
#黑色虛線(k--)寬度1.5(lw=1.5)繪制垂直線
plt.plot([x0,x0],[0,y0],'k--',lw=1.5)
添加標注
給一個點添加標注
方法
plt.annotate(str,xy=,xycoords=,xytext=,textcoords=,fontsize=,arrowprops=dict(arrowstyle=,connectionstyle=))
示例
plt.annotate(r'$2x=%s$'%y0,xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords='offset points',fontsize=16,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=0.2'))
相應參數
- str,標注內容
xy
:元組,代表被標注點的坐標xycoords
:字符串,被注釋點的坐標系屬性。默認為'data'
,即以被注釋的坐標點xy
為參考textcoords
:字符串
xycoords
andtextcoords
是坐標xy
與xytext
的說明,若textcoords=None
,則默認textcoords
與xycoords
相同,若都未設置,默認為'data'
上述示例中,xy
(箭頭尖端)和xytext
位置(文本位置)都以數據坐標為單位。 有多種可以選擇的其他坐標系 , 你可以使用xycoords
和textcoords
以及下列字符串之一(默認為data)指定xy和xytext的坐標系。
參數 | 坐標系 | |
---|---|---|
1 | 'figure points' | 距離圖形左下角的點數量 |
2 | 'figure pixels' | 距離圖形左下角的點數量 |
3 | 'figure fraction' | 0,0 是圖形左下角,1,1 是右上角 |
4 | 'axes points' | 距離軸域左下角的點數量 |
5 | 'axes pixels' | 距離軸域左下角的像素數量 |
6 | 'axes fraction' | 0,0 是軸域左下角,1,1 是右上角 |
7 | 'data' | 使用軸域數據坐標系 |
xytext
:元組,代表標注內容相對被標注點的坐標fontsize
:標注內容的大小arrowprops
-
arrowstyle
:字符串,箭頭形狀
-
connectionstyle
:字符串,箭頭弧度
可選參數
相應效果
-
text(x,y,str,fontdict)
示例
plt.text(-3.7,3,r'$This\ is\ a\ text\ \mu\ \sigma_i\ \alpha_t$',fontdict={'size':16,'color':'r'})
參數說明
x
:int or float注釋內容所在位置橫坐標y
:int or float注釋內容所在位置縱坐標str
:str,注釋內容fontdict
,dict'size'
:注釋內容大小'color'
:注釋內容顏色
總代碼及運行結果
代碼
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,500)
y = 2*x
plt.plot(x,y)
#1、設置x,y軸的范圍
plt.xlim((-1,6))
plt.ylim((-6,6))
#2、設置x,y軸的標簽
plt.xlabel("x")
plt.ylabel("y")
#3、設置坐標軸的單位長度
new_ticks = np.linspace(-3,3,7) #范圍從-3到3,划分為6段
plt.xticks(new_ticks)
#4、自定義value,並更改標簽的字體(使用latex語法,注意空格使用\轉義)
plt.yticks([-6,-2,0,2,6],[r'$very\ bad$',r'$plain$',r'$very\ good$',r'$\alpha$'])
#5、隱藏上軸和右軸
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#6、設置x軸為下面的軸,設置y軸為左邊的軸
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
#7、設置原點的坐標
ax.spines['bottom'].set_position(('data',0))#x軸表示為y=0
ax.spines['left'].set_position(('data',1)) #y軸表示為x=1
#8、添加Annotation
## 8.1 添加點和垂直線
x0 = 2
y0 = 2*x0
#繪制對應點
plt.scatter(x0,y0,s=50,color='r')
#黑色虛線寬度1.5繪制垂直線
plt.plot([x0,x0],[0,y0],'k--',lw=1.5)
## 8.2 添加標注
plt.annotate(r'$2x=4$',xy=(x0,y0),xycoords='data',xytext=(+30,-30),textcoords='offset points',fontsize=30,arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
plt.text(-3.7,3,r'$This\ is\ a\ text\ \mu\ \sigma_i\ \alpha_t$',fontdict={'size':16,'color':'r'})
plt.show()
運行結果
備注:部分圖片來自該博客,僅供學習交流使用,侵刪。
Matplotlib中文指南——標注