使用matplotlib.pyplot在直线和x轴之间添加垂直虚线

2024-10-01 07:37:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个情节: enter image description here

我使用annotate方法绘制这些箭头

ax.annotate('sample events', (x_value, y_value), xytext=(x_value, -3000), rotation=90, va='top', arrowprops = {'width': 2, 'headwidth': 4, 'linestyle': '--'})

但我想要的是: enter image description here

如果注释文本在x轴上会更好,有什么办法吗

(我试过ax.axvline(x=x_值),但它会在整个绘图中形成垂直线)


Tags: sample方法valuetop绘制箭头axevents
2条回答

简单的方法是使用ax.stem,例如:

import matplotlib.pyplot as plt
import numpy as np

y = np.random.random(20)

fig, ax = plt.subplots()
ax.plot(y)
ax.stem(y, markerfmt='.')
plt.show()

生成的示例图为:

enter image description here

如果要隐藏水平线,请使用basefmt = " "

ax.stem(y, basefmt = " ", markerfmt='.')

首先:您应该避免代码中的#,因为它将被解释为comment

根据ax.annotatedocumentation,您应该轻松地将线型指定为虚线,以及标签的位置可以在here找到一个很好的示例列表。

您应该尝试类似的方法:ax.annotate('dashed line', xy=(0.25,0.2), xytext=(0.6,0.2),arrowprops={'arrowstyle': '-', 'ls': 'dashed'}, va='center', rotate=90)

相关问题 更多 >