我正在尝试在图中注释文本,以便它们遵循线的曲率。我有以下情节:
这就是我想要获得的,如果我为注释修复了一个特定的y值,对于每条曲线,它应该沿着曲线将注释放在所需的斜率上(即它应该遵循曲线的曲率)如下所示:
没有注释的绘图的可重现代码是:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([[53.4, 57.6, 65.6, 72.9],
[60.8, 66.5, 73.1, 83.3],
[72.8, 80.3, 87.2, 99.3],
[90.2, 99.7, 109.1, 121.9],
[113.6, 125.6, 139.8, 152]])
y = np.array([[5.7, 6.4, 7.2, 7.8],
[5.9, 6.5, 7.2, 7.9],
[6.0, 6.7, 7.3, 8.0],
[6.3, 7.0, 7.6, 8.2],
[6.7, 7.5, 8.2, 8.7]])
plt.figure(figsize=(5.15, 5.15))
plt.subplot(111)
for i in range(len(x)):
plt.plot(x[i, :] ,y[i, :])
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
如何使用matplotlib在Python中放置此类文本?
答案 0 :(得分:5)
你可以用度数获得渐变,并在matplotlib.text.Text中使用旋转参数
rotn = np.degrees(np.arctan2(y[:,1:]-y[:,:-1], x[:,1:]-x[:,:-1]))
编辑:所以它比我建议的有点麻烦,因为绘图区域被缩放以匹配数据并具有边距等但你明白了
...
plt.figure(figsize=(7.15, 5.15)) #NB I've changed the x size to check it didn't distort
plt.subplot(111)
for i in range(len(x)):
plt.plot(x[i, :] ,y[i, :])
rng = plt.axis()
x_scale = 7.15 * 0.78 / (rng[1] - rng[0])
y_scale = 5.15 * 0.80 / (rng[3] - rng[2])
rotn = np.degrees(np.arctan2((y[:,1:]-y[:,:-1]) * y_scale,
x[:,1:]-x[:,:-1]) * x_scale)
labls = ['first', 'second', 'third', 'fourth', 'fifth']
for i in range(len(x)):
plt.annotate(labls[i], xy=(x[i,2], y[i,2]), rotation=rotn[i,2])
plt.xlabel('X')
RE-EDIT注意到缩放是错误的,但恰巧巧合!此外,由于缩放,标签的xy值有点近似。