matplotlib matplotlib中在图像中添加注释的用法——annotate
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# 绘制一个余弦曲线
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),
xycoords='data',
arrowprops=dict(facecolor='black', shrink=0.05)
)
ax.set_ylim(-2, 2)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# 以步长0.005绘制一个曲线
x = np.arange(0, 10, 0.005)
y = np.exp(-x/2.) * np.sin(2*np.pi*x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 10)
ax.set_ylim(-1, 1)
# 被注释点的数据轴坐标和所在的像素
xdata, ydata = 5, 0
xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata))
# 设置注释文本的样式和箭头的样式
bbox = dict(boxstyle="round", fc="0.8")
arrowprops = dict(
arrowstyle = "->",
connectionstyle = "angle,angleA=0,angleB=90,rad=10")
# 设置偏移量
offset = 72
# xycoords默认为'data'数据轴坐标,对坐标点(5,0)添加注释
# 注释文本参考被注释点设置偏移量,向左2*72points,向上72points
ax.annotate('data = (%.1f, %.1f)'%(xdata, ydata),
(xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points',
bbox=bbox, arrowprops=arrowprops)
# xycoords以绘图区左下角为参考,单位为像素
# 注释文本参考被注释点设置偏移量,向右0.5*72points,向下72points
disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay),
(xdisplay, ydisplay), xytext=(0.5*offset, -offset),
xycoords='figure pixels',
textcoords='offset points',
bbox=bbox, arrowprops=arrowprops)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# 绘制一个极地坐标,再以0.001为步长,画一条螺旋曲线
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(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), # 被注释点遵循极坐标系,坐标为角度和半径
xytext=(0.05, 0.05), # 注释文本放在绘图区的0.05百分比处
textcoords='figure fraction',
arrowprops=dict(facecolor='black', shrink=0.05),# 箭头线为黑色,两端缩进5%
horizontalalignment='left',# 注释文本的左端和低端对齐到指定位置
verticalalignment='bottom',
)
plt.show()
import matplotlib.pyplot as plt
# 设置绘图区标题
fig = plt.figure()
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
# 设置子绘图区标题
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
ax.set_title('axes title')
# 设置x y坐标轴的标识
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
# 红色、透明度0.5、边框留白10
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})
# 文字中有数学公式
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
# 文字中有ASCII码
ax.text(3, 2, 'unicode: Institut f\374r Festk\366rperphysik')
# 转换坐标系
ax.text(0.95, 0.01, 'colored text in axes coords',
verticalalignment='bottom', horizontalalignment='right',
transform=ax.transAxes,
color='green', fontsize=15)
# 在2,1处画个圆点,添加注释
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05))
ax.axis([0, 10, 0, 10])
plt.show()