如何在 Matplotlib Pyplot 中显示网格
本教程介绍了如何在 Python Matplotlib 中在图上画一个网格。我们将使用 grid()
函数来实现这一目的。它还演示了如何使用 grid()
函数参数来自定义网格的颜色和形状,甚至只画垂直或水平线。
在 Matplotlib 中绘制正态分布图
让我们先创建两个列表来表示 x 和 y 值,并使用它们来绘制一个图。调用 plot()
函数并传递 x 和 y 列表作为参数,然后调用 show()
函数。
使用 title()
、xlabel
和 ylabel()
函数为你的图添加标题和标签,使其易于理解。
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()
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串