matplotlib7 --文字註釋 annotate() and text()

圖的文字註釋:

  1. annotate()
  2. text()

1. Axes.annotate(s, xy, *args, **kwargs)

用text s註釋point xy

參數:

  • s : str 註釋文本
  • xy: (float, float) 要註釋的點(x, y)
  • xytext: (float, float) optional s顯示的位置。 默認xy
  • xycoords: xy所採用的座標系, 默認是’data’
    在這裏插入圖片描述
  • textcoords: xytext所採用的位置確定方法
    在這裏插入圖片描述

默認是xycoords,既採用和xycoords一樣的座標系統。

  • arrowprops: 在xy和xytext之間指向箭頭的屬性 參數類型爲dict

    1. 如果 字典中沒有’arrowstyle’ 鍵,則使用一下鍵值
      在這裏插入圖片描述

      matplotlib.patches.FancyArrowPatch

    2. 如果包含’arrowstyle’, 則使用一下鍵值
      允許的arrowstyle包括:
      在這裏插入圖片描述

      有效的鍵包括:
      在這裏插入圖片描述

      matplotlib.patches.PathPatch

  • annotation_clip
    當xy在Axes區域外時,是否還要註釋

    • True: 只有當xy在Axes內是才註釋
    • False: 註釋總是會被添加
    • None:只有xy在Axes內並且xycoords是’data’才註釋
      **kwargs
      其餘的參數都傳給Text

在之後的文章中會進一步介紹箭頭的屬性設置等更深入的話題

  1. 先看一個簡單的例子:

fig = plt.figure()
ax = fig.add_subplot(111)

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)


ann = ax.annotate("local max",
                  xy=(2, 1), xycoords='data',
                  xytext=(3, 1.5), textcoords='data',
                  
                  # 設置字體相關屬性
                  size=20, va="center", ha="center",
                  color='r',
                  bbox=dict(boxstyle="round4", fc="w"),

                  arrowprops=dict(arrowstyle="-|>",
                                  connectionstyle="arc3,rad=-0.2",
                                  fc="w"), 
                  )

ax.set_ylim(-2,2)
plt.show()

在這裏插入圖片描述

  1. 一個相對完整的作圖例子
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-np.pi, np.pi, 128,endpoint=True)
cosx,sinx,x_3 = np.cos(x), np.sin(x), x / 3

#%%
fig = plt.figure(1)
axes0 = plt.subplot(111)
line1, line2 = axes0.plot(x, cosx, 'r',x, sinx, 'c')

line1.set_linewidth(2.5)
line2.set_linewidth(1)
# plt.xlim(x.min() *2, x.max()*2)
axes0.set_xlim(x.min() *1.2, x.max()*1.2)
axes0.set_ylim(cosx.min() * 1.2, cosx.max() * 1.2)

axes0.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
axes0.set_xticklabels([r'$-\pi$', r'$-\frac{\pi}{2}$', 0,  r'$+\frac{\pi}{2}$', r'$+\pi$'])
axes0.set_yticks([-1, 0, 1])
axes0.set_yticklabels([r'-1', r'0', r'+1'])

# add legend
axes0.legend([line1, line2], ['y=cos(x)', 'y=sin(x)'])

# 軸居中
axes0.spines['right'].set_color('none')
axes0.spines['top'].set_color('none')
axes0.xaxis.set_ticks_position('bottom')
axes0.spines['bottom'].set_position(('data',0))
axes0.yaxis.set_ticks_position('left')
axes0.spines['left'].set_position(('data',0))
# 添加註釋
t = 2 * np.pi / 3

# 通過將[t, 0], [t, np.sin(t)]連接起來使得圖更好看一些。
axes0.plot([t, t], [0, np.sin(t)], color='c', linewidth=1.5, linestyle="--")
axes0.scatter([t],[np.sin(t)] ,s=50, c='c')
axes0.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
              xy=(t, np.sin(t)), xycoords='data',
              xytext=(+10, +30), textcoords='offset points',
              fontsize=16, color= 'c',
              arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

# 同樣對cosx做處理
axes0.plot([t, t], [0, np.cos(t)], color='r', linewidth=1.5, linestyle="--")
axes0.scatter([t],[np.cos(t)] ,s=50, c='r')
axes0.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
              xy=(t, np.cos(t)), xycoords='data',
              xytext=(-90, -50), textcoords='offset points',
              fontsize=16, color= 'r',
              arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.show()

在這裏插入圖片描述

  1. 看一個極座標系的作圖
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)

r = np.arange(0, 1, 0.001)

theta = 2 *2 * np.pi * r

# 前兩個是特例
# line, = ax.plot([4*np.pi]*1000, r, color='#ee8d18', lw=3)
# line, = ax.plot(theta, [1]*1000, color='#ee8d18', lw=3)

line, = ax.plot(theta, r, color='#ee8d18', lw=3)

# 在第800個點出註釋
ind = 800
thisr, thistheta = r[ind], theta[ind]
ax.plot([thistheta], [thisr], 'o')

ax.annotate('a polar annotation',
            xy=(thistheta, thisr),  # theta, radius
            xytext=(0.1, 0.1),    # fraction, fraction
            textcoords='figure fraction',  # 從左下角開始,註釋文字起始位置所佔Figure總長度的比例(0~1)
            horizontalalignment='left',
            verticalalignment='bottom',
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")
            )
plt.show()

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章