【matplotlib】可視化解決方案——如何正確使用文本注釋

概述

注釋是圖形元素,通常是文本片段,用于解釋、添加上下文或以其他方式突出顯示可視化數(shù)據(jù)的某些部分。文本注釋的展示效果在很大程度上受文本注釋位置的影響,而且,文本注釋位置又由于采用的坐標(biāo)系統(tǒng)的不同而呈現(xiàn)出不同的文本移動(dòng)情況。接下來,本文將會(huì)詳細(xì)介紹文本注釋位置的坐標(biāo)系統(tǒng)。

matplotlib 的注釋一共有兩種,第一種是無指向型注釋 text();另一種是指向型注釋 annotate()。本文將主要介紹 annotate(),該方法的定義如下:

def Axes.annotate(text, xy, xytext=None, xycoords='data', 
textcoords=None, arrowprops=None,
 annotation_clip=None, **kwargs)

參數(shù)說明:

  1. text:要注釋的文字;
  2. xy:指定要注釋的點(diǎn);
  3. xytext:放置文本的位置;
  4. xycoords:指定注釋點(diǎn)的坐標(biāo)系;
  5. textcoords:指定注釋文字的坐標(biāo)系;
  6. arrowprops:指定從文字注釋位置出發(fā)到注釋點(diǎn)之間的箭頭屬性;
  7. annotation_clip:指定當(dāng)標(biāo)注點(diǎn)在坐標(biāo)軸區(qū)域外時(shí)的處理方法;
  8. kwargs:傳遞關(guān)鍵字參數(shù)給 Text類;

返回值:Annotation實(shí)例。

annotate() 方法主要需要定義三個(gè)東西,第一個(gè)是注釋點(diǎn);第二個(gè)是注釋文字和其屬性;最后一個(gè)是中間箭頭的相關(guān)屬性。使用該方法的難點(diǎn)在于 xycoordstextcoords 參數(shù)的設(shè)置,前者可能的取值如下:

描述
figure points 相對(duì)于圖像左下角的點(diǎn)數(shù)(points)
figure pixels 相對(duì)于圖像左下角的像素?cái)?shù)(pixels)
figure fraction 相對(duì)于圖像左下角的比例,(0, 0) 為圖像左下角; (1, 1) 為右上角
subfigure points 相對(duì)于子圖左下角的點(diǎn)數(shù)(points)
subfigure pixels 相對(duì)于子圖左下角的像素?cái)?shù)(pixels)
subfigure fraction 相對(duì)于子圖左下角的比例
axes points 相對(duì)圖坐標(biāo)軸的點(diǎn)數(shù)(points)
axes pixels 相對(duì)圖坐標(biāo)軸的像素?cái)?shù)(pixels)
axes fraction 相對(duì)圖坐標(biāo)軸的比例
data 默認(rèn)值,使用被注解對(duì)象的坐標(biāo)系
polar 極坐標(biāo)系

一般情況下我們就使用默認(rèn)值就好了,因?yàn)橄鄬?duì)于注解對(duì)象的坐標(biāo)系理解起來最為容易。textcoords 參數(shù)可能的取值就簡(jiǎn)單了,默認(rèn)情況下和 xycoords 參數(shù)指定的模式一致,除此之外還可以設(shè)置是按點(diǎn)偏移還是按像素偏移。

示例

我們首先以一個(gè)簡(jiǎn)單的例子開始,給出數(shù)據(jù)標(biāo)注位置和注釋文本位置,這兩個(gè)參數(shù)都傳遞一個(gè)元祖。完整代碼如下:

import numpy as np  
import matplotlib.pyplot as plt  
  
fig, ax = plt.subplots(figsize=(3, 3))  
  
t = np.arange(0.0, 5.0, 0.01)  
s = np.cos(2*np.pi*t)  
line, = ax.plot(t, s, lw=2)  
  
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),  
            arrowprops=dict(facecolor='black', shrink=0.05))  
ax.set_ylim(-2, 2)  
  
plt.show()

畫圖結(jié)果:

基本示例

接著我們更改注釋文字使用的坐標(biāo)系為 axes fraction,傳遞元祖 (0.01, 0.99),那么文字注釋就會(huì)在左上角。完整代碼如下:

import numpy as np  
import matplotlib.pyplot as plt  
  
fig, ax = plt.subplots(figsize=(3, 3))  
  
t = np.arange(0.0, 5.0, 0.01)  
s = np.cos(2*np.pi*t)  
line, = ax.plot(t, s, lw=2)  
  
ax.annotate('local max', xy=(2, 1), xycoords='data',  
            xytext=(0.01, .99), textcoords='axes fraction',  
            va='top', ha='left',  
            arrowprops=dict(facecolor='black', shrink=0.05))  
ax.set_ylim(-2, 2)  
  
plt.show()

畫圖結(jié)果如下:

文字注釋放置在左上角

不光可以在一個(gè) Axes 對(duì)象中注釋,也可以在多個(gè) Axes 對(duì)象中注釋,完整的示例代碼如下:

import numpy as np  
import matplotlib.pyplot as plt  
  
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(6, 3))  
  
ax1.annotate("Test1", xy=(0.5, 0.5), xycoords="axes fraction")  
ax2.annotate("Test2",  
               xy=(0.5, 0.5), xycoords=ax1.transData,  
               xytext=(0.5, 0.5), textcoords=ax2.transData,  
               arrowprops=dict(arrowstyle="->"))  
  
plt.show()

畫圖結(jié)果:

跨子圖注釋

最后將 annotate() 方法做一個(gè)綜合演示,包括箭頭樣式、文字樣式、坐標(biāo)軸等,其中箭頭樣式等內(nèi)容將會(huì)在可視化之路專欄詳細(xì)講解完整代碼如下:

import matplotlib.pyplot as plt  
  
from basic_units import cm  
from matplotlib.patches import Ellipse  
  
fig, ax = plt.subplots(1, 1)  
font_style = {"family": "monospace", "fontsize": 15, "weight": "bold"}  
ellipse = Ellipse((2 * cm, 1 * cm), 0.05 * cm, 0.05 * cm, color='blue')  
ax.add_patch(ellipse)  
  
ax.annotate("fancy1", xy=(2 * cm, 1 * cm), xycoords='data', xytext=(0.8 * cm, 0.85 * cm), textcoords='data',  
            bbox=dict(boxstyle='round', fc='w', ec='k'),  
            arrowprops=dict(arrowstyle="fancy,head_length=0.4,head_width=0.4,tail_width=0.6", fc="gray",  
                            connectionstyle='arc3,rad=0.3', shrinkA=5, patchB=ellipse, shrinkB=5), ha='right', va='top',  
            **font_style)  
  
ax.annotate("fancy2", xy=(2 * cm, 1 * cm), xycoords='data', xytext=(0.8 * cm, 0.85 * cm), textcoords='axes fraction',  
            bbox=dict(boxstyle='round', fc='w', ec='k'),  
            arrowprops=dict(arrowstyle="fancy,head_length=0.4,head_width=0.4,tail_width=0.6", fc="gray",  
                            connectionstyle='arc3,rad=0.3', shrinkA=5, patchB=ellipse, shrinkB=5), ha='right', va='top',  
            **font_style)  
  
ax.set_xlim([0 * cm, 3 * cm])  
ax.set_ylim([0 * cm, 3 * cm])  
plt.show()

畫圖結(jié)果:

綜合示例

往期回顧

  1. 【matplotlib】可視化解決方案——如何調(diào)整計(jì)量單位和計(jì)量方法
  2. 【matplotlib】可視化解決方案——如何實(shí)現(xiàn)圖形的動(dòng)畫效果
  3. 【matplotlib】可視化解決方案——如何正確使用plot方法
  4. 【matplotlib】可視化解決方案——如何向畫布中添加坐標(biāo)軸
  5. 【matplotlib】可視化解決方案——如何正確使用matplotlib顏色系統(tǒng)
  6. 【matplotlib】可視化解決方案——如何實(shí)現(xiàn)畫布局部放大功能
  7. 【matplotlib】可視化解決方案——如何更改matplotlib配置信息
  8. 【matplotlib】可視化解決方案——如何定制化網(wǎng)格
  9. 【matplotlib】可視化解決方案——如何向畫布添加交叉直線
  10. 【matplotlib】可視化解決方案——如何解決matplotlib中文亂碼問題

文中難免會(huì)出現(xiàn)一些描述不當(dāng)之處(盡管我已反復(fù)檢查多次),歡迎在留言區(qū)指正,相關(guān)的知識(shí)點(diǎn)也可進(jìn)行分享,希望大家都能有所收獲!!如果覺得我的文章寫得還行,不妨支持一下。你的每一個(gè)轉(zhuǎn)發(fā)、關(guān)注、點(diǎn)贊、評(píng)論都是對(duì)我最大的支持!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容