迹忆客 专注技术分享

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

如何在 Matplotlib Pyplot 中显示网格

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

本教程介绍了如何在 Python Matplotlib 中在图上画一个网格。我们将使用 grid() 函数来实现这一目的。它还演示了如何使用 grid() 函数参数来自定义网格的颜色和形状,甚至只画垂直或水平线。


在 Matplotlib 中绘制正态分布图

让我们先创建两个列表来表示 x 和 y 值,并使用它们来绘制一个图。调用 plot() 函数并传递 x 和 y 列表作为参数,然后调用 show() 函数。

使用 title()xlabelylabel() 函数为你的图添加标题和标签,使其易于理解。

from matplotlib import pyplot as plt

x = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
y = [200, 300, 300, 350, 380, 450, 500, 500, 520, 525, 530]

plt.title("MyPlot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")

plt.plot(x, y)
plt.show()

但是,普通的画图似乎很无聊,缺少了一些东西。现在,我们需要给我们的绘图添加一个网格。


在 Matplotlib 中的绘图中使用 grid()

我们将使用 Matplotlib grid() 函数在图上画一个网格。

我们需要在 show() 之前调用 grid() 函数,这样就会在前面的图上画出一个网格。

请看下面的代码。

from matplotlib import pyplot as plt

x = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
y = [200, 300, 300, 350, 380, 450, 500, 500, 520, 525, 530]

plt.title("MyPlot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")

plt.plot(x, y)
plt.grid()
plt.show()

改变 Matplotlib 中的网格属性

grid() 函数接受参数来定制网格的颜色和样式。我们可以像 grid(color='r', linestyle='dotted', linewidth=1) 这样调用 grid() 来得到一个红色、点状和细线的网格。

from matplotlib import pyplot as plt

x = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
y = [200, 300, 300, 350, 380, 450, 500, 500, 520, 525, 530]

plt.title("MyPlot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")

plt.plot(x, y)
plt.grid(color="r", linestyle="dotted", linewidth=1)
plt.show()

线宽是浮动数据类型,这里有所有的颜色代码和线型供你选择。

有效的颜色代码。

代码 颜色
b 蓝色
g 绿化
r 红色
c 青色
m 洋红色
y
k 黑色
w 白色

有效的行式。

  • -
  • --
  • -.
  • :
  • None
  •  
  • ``
  • solid
  • dashed
  • dashdot
  • dotted

绘制垂直或水平线

grid() 函数的默认值是同时绘制水平轴和垂直轴,但你可能也想自定义它。你可以使用 axis 参数来实现这一点。调用 grid() 时,使用 axis='x'只画垂直线,或者 axis='y'只画水平线,或者 axis='both'两者都画,这是默认选项。

请看下面的代码和它的输出。

from matplotlib import pyplot as plt

x = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
y = [200, 300, 300, 350, 380, 450, 500, 500, 520, 525, 530]

_, (a, b, c) = plt.subplots(1, 3)

a.grid(axis="y", linestyle="dotted", color="b")
a.plot(x, y)
a.set_title("axis='y'")

b.grid(axis="x", linestyle="dotted", color="b")
b.plot(x, y)
b.set_title("axis='x'")

c.grid(axis="both", linestyle="dotted", color="b")
c.plot(x, y)
c.set_title("axis='both'")

plt.show()

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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便