1. 程式人生 > >Annotation 標註

Annotation 標註

ott $2 ins cat rds .sh 箭頭 text 虛線

1、畫出基本圖

當圖線中某些特殊地方需要標註時,我們可以使用 annotation. matplotlib 中的 annotation 有兩種方法, 一種是用 plt 裏面的 annotate,一種是直接用 plt 裏面的 text來寫標註.

首先,我們在坐標軸中繪制一條直線.

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> x = np.linspace(-3, 3, 50)
>>> y = 2*x + 1
>>> plt.figure(num=1, figsize=(8, 5),)
<Figure size 800x500 with 0 Axes> >>> plt.plot(x, y,) [<matplotlib.lines.Line2D object at 0x000001C38F2B4C88>] >>> plt.show()

技術分享圖片

2、移動坐標

然後我們挪動坐標軸的位置.

>>> ax = plt.gca()
>>> ax.spines[right].set_color(none)
>>> ax.spines[top].set_color(none)
>>> ax.spines[
top].set_color(none) >>> ax.xaxis.set_ticks_position(bottom) >>> ax.spines[bottom].set_position((data, 0)) >>> ax.yaxis.set_ticks_position(left) >>> ax.spines[left].set_position((data, 0)) >>> plt.show()

技術分享圖片

然後標註出點(x0, y0)的位置信息. 用plt.plot([x0, x0,], [0, y0,], ‘k--‘, linewidth=2.5)

畫出一條垂直於x軸的虛線.

>>> x0 = 1
>>> y0 = 2*x0 + 1
>>> plt.plot([x0, x0,], [0, y0,], k--, linewidth=2.5)
[<matplotlib.lines.Line2D object at 0x000001C38E026748>]
>>> # set dot styles
... plt.scatter([x0, ], [y0, ], s=50, color=b)
<matplotlib.collections.PathCollection object at 0x000001C38E018320>
>>> plt.show()

技術分享圖片

3、添加註釋 annotate

接下來我們就對(x0, y0)這個點進行標註.

plt.annotate(r$2x+1=%s$ % y0, xy=(x0, y0), xycoords=data, xytext=(+30, -30),
             textcoords=offset points, fontsize=16,
             arrowprops=dict(arrowstyle=->, connectionstyle="arc3,rad=.2"))
             
plt.show()

其中參數xycoords=‘data‘ 是說基於數據的值來選位置, xytext=(+30, -30)textcoords=‘offset points‘ 對於標註位置的描述 和 xy 偏差值, arrowprops是對圖中箭頭類型的一些設置.

技術分享圖片

4、添加註釋text

plt.text(-3.7, 3, r$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$,
         fontdict={size: 16, color: r})

其中-3.7, 3,是選取text的位置, 空格需要用到轉字符\ ,fontdict設置文本字體.

技術分享圖片

Annotation 標註