如何在 Matplotlib 中的图形上添加网格?
Matplotlib 库广泛用于绘制图形。在很多图中,我们需要有网格来提高可读性。网格是通过使用 pyplot 子库中的 grid()函数创建的。
grid() :配置网格线。
Syntax:
matplotlib.pyplot.grid(b=None, which=’major’, axis=’both’, **kwargs)
Parameters:
- b: bool or None, optional parameter for Whether to show the grid lines.
- which : {‘major’, ‘minor’, ‘both’}, optional. It specifies the grid lines to apply the changes on.
- axis : {‘both’, ‘x’, ‘y’}, optional. The axis to apply the changes on.
- **kwargs : Optional. Specify Line properties such as color, line style, line width, etc.
脚步:
- 绘制图形
- 使用 pyplot.grid() 方法指定网格。
示例 1:
Python3
import matplotlib.pyplot as plt
import numpy
# Define x and y
x = numpy.arange(0, 1, 0.1)
y = numpy.power(x, 2)
# Plot graph
plt.scatter(x, y)
# Define grid with axis='y'
plt.grid(axis='y')
plt.show()
# Define a figure
fig = plt.figure()
ax = fig.gca()
# Set labels on x and y axis of figure
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1, 0.1))
# Plot the graph
ax.scatter(x, y)
# Specify default grid on figure
ax.grid()
ax.show()
Python3
import matplotlib.pyplot as plt
import numpy as np
# Define x and y
x = np.arange(-5, 5, 0.01)
y = np.sin(2*np.pi*x)
# Plot line graph
plt.plot(x, y)
# Specify grid with line attributes
plt.grid(color='r', linestyle='--')
# Display the plot
plt.show()
输出:
示例 2:
蟒蛇3
import matplotlib.pyplot as plt
import numpy as np
# Define x and y
x = np.arange(-5, 5, 0.01)
y = np.sin(2*np.pi*x)
# Plot line graph
plt.plot(x, y)
# Specify grid with line attributes
plt.grid(color='r', linestyle='--')
# Display the plot
plt.show()
输出: