天天看點

Matplotlib在圖形中添加文本說明添加文本說明

添加文本說明

很多時候我們需要在圖形中添加說明文本,來凸顯圖中點或線的重要性。

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 8, 1000)
y = 2.0 * x + 0.5 * 5 * x ** 2
plt.title('Acceleration Moving')
plt.xlabel('Time')
plt.ylabel('distance')
plt.scatter(x[0],y[0])
plt.text(x[0], y[0], 'start')
plt.plot(x, y, c = 'c')
plt.show()      
Matplotlib在圖形中添加文本說明添加文本說明

Tips:plt.text() 函數接受要顯示的位置和文本作為參數。位置以坐标形式給出,其指定了文本框左下角的位置。

文本的對齊方式

文本外圍包含隐式文本框(下文會介紹文本框的顯示方法),此框用于将文本與傳遞給 plt.text() 的坐标進行相對對齊。使用 verticalalignment 和 horizontalalignment 參數(它們分别可以簡寫為 va 和 ha )控制對齊的方式。

垂直對齊選項如下所示:

參數值 說明
center 參數坐标相對于文本框的中心
top 參數坐标相對于文本框的上側
bottom 參數坐标相對于文本框的底部
baseline 參數坐标相對于文本的基線
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 8, 1000)
y = 2.0 * x + 0.5 * 5 * x ** 2
x_b = np.linspace(0, 8, 1000)
y_b = np.zeros_like(x_b)
plt.title('Acceleration Moving')
plt.xlabel('Time')
plt.ylabel('distance')
plt.scatter(x[0],y[0])
plt.text(0, 0, 'center', va='center')
plt.text(2, 0, 'top', va='top')
plt.text(4, 0, 'bottom', va='bottom')
plt.text(6, 0, 'baseline', va='baseline')
plt.plot(x, y, c = 'c')
plt.plot(x_b, y_b, c = 'm')
plt.show()      
Matplotlib在圖形中添加文本說明添加文本說明

水準對齊選項如下所示:

left 參數坐标相對于文本框的左側
right 參數坐标相對于文本框的右側
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 8, 1000)
y = 2.0 * x + 0.5 * 5 * x ** 2
y_b = np.linspace(0, 100, 1000)
x_b = np.zeros_like(y_b)
plt.title('Acceleration Moving')
plt.xlabel('Time')
plt.ylabel('distance')
plt.scatter(x[0],y[0])
plt.text(0, 0, 'center', ha='center')
plt.text(0, 50, 'left', ha='left')
plt.text(0, 100, 'right', ha='right')
plt.plot(x, y, c = 'c')
plt.plot(x_b, y_b, c = 'm')
plt.show()      
Matplotlib在圖形中添加文本說明添加文本說明

文本邊界框

上文介紹了文本外圍包含隐式文本框,為了可以顯式的繪制文本框,plt.plot() 支援一個以字典為輸入的 bbox 參數,此詞典用于定義文本框的外觀配置:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 8, 1000)
y = 2.0 * x + 0.5 * 5 * x ** 2
box = {
    'facecolor': '.75',
    'edgecolor': 'r',
    'boxstyle': 'round'
}
plt.title('Acceleration Moving')
plt.text(0, 8, 'start', bbox=box)
plt.plot(x, y, c = 'c')
plt.show()      
Matplotlib在圖形中添加文本說明添加文本說明

bbox 參數的字典定義包含以下常見鍵值對:

說明與可選值
facecolor 用于設定文本框背景和邊的顔色
edgecolor 用于設定文本框邊緣的顔色
alpha 用于設定透明度級别,使文本框與背景更好的混合
boxstyle 設定文本框的樣式,可選值包括 "round" 和 "square"
pad 如果 "boxstyle" 設定為 "square",則它定義文本和文本框邊之間的填充量