【问题标题】:Plot vertical lines in matplotlib within a given y range [duplicate]在给定的y范围内绘制matplotlib中的垂直线[重复]
【发布时间】:2021-10-26 13:30:47
【问题描述】:

我正在使用以下内容:

fig, ax = plt.subplots(figsize=(20, 10))

ax.set_ylim(bottom=0, top=10)
for i in range(4):
    ax.axvline(x=i, ymin=5, ymax=9, color="red", linewidth=40)

这给出了:

我希望从y = 5y = 9 的每一点都有一条垂直线。

【问题讨论】:

  • 请参阅 docs 以获取预期值 yminymax。使用vlines 而不是axvline

标签: python matplotlib plot data-visualization visualization


【解决方案1】:

您应该使用 matplotlib.pyplot.vlines,正如 BigBen 在评论中所建议的那样:

for i in range(4):
    ax.vlines(x=i, ymin=5, ymax=9, color="red", linewidth=40)

【讨论】:

  • 你说得对,更新答案,谢谢
【解决方案2】:

如果您查看 axvline 的参数,您会发现 ymin 和 ymax 从 0 变为 1。您的完整 ylimit 的一小部分。 https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.axvline.html

因此,您需要 0.5 到 .9 之类的值或计算适当的分数。

fig, ax = plt.subplots(figsize=(20, 10))

ax.set_ylim(bottom=0, top=10)
for i in range(4):
    ax.axvline(x=i, ymin=.5, ymax=.9, color="red", linewidth=40)

输出:

【讨论】: