在 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()
当窗口很小时,生成带有随机网格的图:
或者根本没有网格,当它更大时:
如何得到0.25间距的均匀网格?
请注意,我打算在循环中使用此代码片段,这就是为什么您会看到
plt.clf()
等。
默认情况下,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()