迹忆客 专注技术分享

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

如何在 Matplotlib 中画一条任意线

作者:迹忆客 最近更新:2024/02/01 浏览次数:

本教程介绍了我们如何在 Matplotlib 中使用 matplotlib.pyplot.plot() 方法、matplotlib.pyplot.vlines() 方法或 matplotlib.pyplot.hlines() 方法和 matplotlib.collections.LineCollection 来绘制任意线条。


Matplotlib 使用 matplotlib.pyplot.plot() 方法绘制一条任意线

我们可以使用 matplotlib.pyplot.plot() 方法简单地绘制一条线。一般来说,绘制从 (x1,y1) 开始到 (x2,y2) 结束的任何一条线的语法是。

plot([x1, x2], [y1, y2])
import matplotlib.pyplot as plt

plt.plot([3, 5], [1, 6], color="green")
plt.plot([0, 5], [0, 5], color="red")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Plot with 2 arbitrary Lines")
plt.show()

输出:

Matplotlib 使用 plot 方法绘制一条任意的直线

它在图中画两条任意线。第一条线用绿色表示,从 (3,1) 延伸到 (5,6),第二条线用红色表示,从 (0,0) 延伸到 (5,5)


Matplotlib 使用 hlines()vlines() 方法绘制任意线

使用 hlines()vlines() 方法绘制任何线条的一般语法是。

vlines(x, ymin, ymax)
hlines(y, xmin, xmax)
import matplotlib.pyplot as plt

plt.hlines(3, 2, 5, color="red")
plt.vlines(6, 1, 5, color="green")
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Plot arbitrary Lines")
plt.show()

输出:

Matplotlib 使用 hlines 和 vlines 方法绘制一条任意线

hlines() 方法用红色画一条水平线,其 Y 坐标在整条线上保持 3,X 坐标从 2 延伸到 5vlines() 方法用绿色画一条垂直线,其 X 坐标在整条线上保持 6,Y 坐标从 1 延伸到 5


Matplotlib 使用 matplotlib.collections.LineCollection 绘制任意线

import matplotlib.pyplot as plt
from matplotlib import collections

line_1 = [(1, 10), (6, 9)]
line_2 = [(1, 7), (3, 6)]

collection_1_2 = collections.LineCollection([line_1, line_2], color=["red", "green"])

fig, axes = plt.subplots(1, 1)
axes.add_collection(collection_1_2)
axes.autoscale()
plt.show()

输出:

Matplotlib 使用 LineCollection 绘制一条任意的线

它从 line_1line_2 中创建线条集合,然后将集合添加到图中。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便