为什么这个 matplotlib 脚本中没有显示网格?

问题描述 投票:0回答:1

在 Ubuntu 22.04 上使用 Python 3.12 和 Matplotlib 3.8.4。我希望看到一个间距为 0.25 的均匀网格。这个片段:

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

gridSpacing = MultipleLocator(0.25)
plt.clf()
plt.gca().set_aspect('equal')
plt.gca().xaxis.set_minor_locator(gridSpacing)
plt.gca().yaxis.set_minor_locator(gridSpacing)
plt.gca().grid(which='minor', axis='both')
plt.plot([1, 2, 3], color='r', linewidth=1, marker='o')
plt.show()

当窗口很小时,生成带有随机网格的图:

enter image description here

或者根本没有网格,当它更大时:

enter image description here

如何得到0.25间距的均匀网格?

请注意,我打算在循环中使用此代码片段,这就是为什么您会看到

plt.clf()
等。

python matplotlib grid
1个回答
0
投票

默认情况下,plt.gca().grid() 仅适用于主要刻度,如果which='major'(或未指定)。为了使次网格线间隔 0.25 一致,您需要在两个轴上显式启用次网格。 这可能有帮助

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

grid_spacing = MultipleLocator(0.25)

plt.clf()  # Clear the figure
fig, ax = plt.subplots()  # Create a new figure and axis

ax.set_aspect('equal')  # Set aspect ratio

# Set both x and y axis minor locators
ax.xaxis.set_minor_locator(grid_spacing)
ax.yaxis.set_minor_locator(grid_spacing)

# Enable the grid for both major and minor ticks
ax.grid(which='both', axis='both', linestyle='--', linewidth=0.5)

# Plotting sample data
ax.plot([1, 2, 3], color='r', linewidth=1, marker='o')

# Set figure size if you are in a loop or want consistent sizing
fig.set_size_inches(6, 6)  # Set desired figure size (in inches)

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.