迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在 Matplotlib 的图上画垂直线

作者:迹忆客 最近更新:2023/03/17 浏览次数:

在处理图表时,我们经常需要在图表上绘制水平线和垂直线来描绘一些信息。它可以是某个平均值、某个阈值或某个范围。本文将讨论如何在 Python 中使用 Matplotlib 生成的图上创建垂直线。

在 Matplotlib 中使用 axvline() 绘制垂直线

axvline() 是来自 Matplotlib 库的一个函数,它沿着轴绘制垂直线。这个函数占用了很多参数,但我们将讨论其中的三个,如下所示。

  • x: The position of the line on the x-axis
  • ymin:该值应介于 0 和 1 之间,其中 0 表示图的底部,1 表示图的顶部。
  • ymax:该值应介于 0 和 1 之间,其中 0 表示图的底部,1 表示图的顶部。

其他参数包括 colorlabelmarkersnaptransformurlvisible 等。

请参阅以下示例以了解如何使用这个函数。

示例 1 - 绘制一条垂直线

import random
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([1, 2, 5, 6, 3, 11, 8, 5, 10, 11])
plt.axvline(x = 5, color = "green", label = "Index 5") # Plotting a single vertical line
plt.plot(x, y, color = "red", label = "Values")
plt.title("Plotting a single vertical line")
plt.xlabel("Indexes")
plt.ylabel("Values")
plt.legend()
plt.show()

输出:

在 matplotlib 中绘制一条垂直线

示例 2 - 绘制多条垂直线

import random
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([1, 2, 5, 6, 3, 11, 8, 5, 10, 11])

for i in range(3):
    plt.axvline(x = random.randint(1, 10), color = np.random.rand(3, )) # Plotting a vertical line

plt.plot(x, y, color = "red", label = "Values")
plt.title("Plotting multiple vertical lines")
plt.xlabel("Indexes")
plt.ylabel("Values")
plt.legend()
plt.show()

输出:

在 matplotlib 中绘制多条垂直线

示例 3 - 具有可变长度的多条线

import random
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
y = np.array([1, 2, 5, 6, 3, 11, 8, 5, 10, 11])
yMins = [1, 0.7, 0.5]
yMaxs = [0.1, 0.4, 0]
positions = [2, 4, 8]

for i in range(3):
    plt.axvline(x = positions[i], ymin = yMins[i], ymax = yMaxs[i], color = np.random.rand(3, )) # Plotting a vertical line

plt.plot(x, y, color = "red", label = "Values")
plt.title("Plotting a multiple vertical lines")
plt.xlabel("Indexes")
plt.ylabel("Values")
plt.legend()
plt.show()

输出:

在 matplotlib 中绘制多条长度可变的垂直线

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便