您可以简单地添加一些文本(MPL Gallery),例如
import matplotlib.pyplot as plt
import numpy as np
x = [1.81,1.715,1.78,1.613,1.629,1.714,1.62,1.738,1.495,1.669,1.57,1.877,1.385]
y = [0.924,0.915,0.914,0.91,0.909,0.905,0.905,0.893,0.886,0.881,0.873,0.873,0.844]
# This is the string that should show somewhere over the plotted line.
line_string = 'name of line'
# plotting
fig, ax = plt.subplots(1,1)
l, = ax.plot(x,y)
pos = [(x[-2]+x[-1])/2., (y[-2]+y[-1])/2.]
# transform data points to screen space
xscreen = ax.transData.transform(zip(x[-2::],y[-2::]))
rot = np.rad2deg(np.arctan2(*np.abs(np.gradient(xscreen)[0][0][::-1])))
ltex = plt.text(pos[0], pos[1], line_string, size=9, rotation=rot, color = l.get_color(),
ha="center", va="center",bbox = dict(ec='1',fc='1'))
def updaterot(event):
"""Event to update the rotation of the labels"""
xs = ax.transData.transform(zip(x[-2::],y[-2::]))
rot = np.rad2deg(np.arctan2(*np.abs(np.gradient(xs)[0][0][::-1])))
ltex.set_rotation(rot)
fig.canvas.mpl_connect('button_release_event', updaterot)
plt.show()
这使
这样你就有了最大的控制权。
请注意,旋转以度为单位,在屏幕而非数据空间中。
更新:
由于我最近需要在缩放和平移时更新的自动标签旋转,因此我更新了我的答案以解决这些需求。现在标签旋转在每次释放鼠标按钮时都会更新(缩放时不会单独触发draw_event )。此方法使用 matplotlib 转换来链接数据和屏幕空间,如本教程中所述。