matplotlib/pandas:在时间序列图中沿线放置标签

6 投票
1 回答
1936 浏览
提问于 2025-04-17 17:55

我正在绘制时间序列数据,比较多个节点的系统特性。我想在某个特定节点的线上明确标记这个节点。到目前为止,我已经成功为这个特定节点设置了不同的线条样式,这样它在图例框中就有了独特的线条和样式标记。

现在我想找到一种方法,在这条线上添加独特的标签,可能是让文字沿着线条弯曲。有没有办法做到这一点呢?

1 个回答

5

让文字沿着线弯曲在matplotlib中并不简单,不过你可以使用annotate这个功能,轻松地在这条线上添加文字和箭头来标记。

比如说:

import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x = np.linspace(0, 20, 200)
y = np.cos(x) + 0.5 * np.sin(3 * x)

fig, ax = plt.subplots()
ax.plot(x, y)

ax.annotate(r'$y = cos(x) + \frac{sin(3x)}{2}$', xy=(x[70], y[70]), 
            xytext=(20, 10), textcoords='offset points', va='center',
            arrowprops=dict(arrowstyle='->'))
plt.show()

在这里输入图片描述

撰写回答