如何实现Matplotlib方形绘图:X/Y轴刻度数相同且轴范围统一
解决Matplotlib方形绘图及轴范围一致问题
你的代码已经设置了ax.set_aspect('equal'),但绘图仍未呈现方形,核心原因是Matplotlib会根据绘制内容自动调整轴的显示范围,导致X、Y轴的实际显示区间不一致。要让X轴和Y轴范围完全一致,只需在代码中强制指定轴的上下限即可。
修改后的完整代码
import matplotlib.pyplot as plt import numpy as np # Step 1: Set the variables groundtruth_position = (0, 0) groundtruth_sigma_x = 1 groundtruth_sigma_y = 2 # Use the maximum value between groundtruth_sigma_x and groundtruth_sigma_y to decide the ticks max_sigma = max(groundtruth_sigma_x, groundtruth_sigma_y) # Calculate the tick range for both axes tick_range = max_sigma * 1.5 # Step 2: Create a figure and plot the groundtruth_position as a single point in black color fig, ax = plt.subplots() ax.scatter(*groundtruth_position, color='black') # Step 3: Set custom ticks for both axes x_ticks = np.arange(groundtruth_position[0] - tick_range, groundtruth_position[0] + tick_range + 1) y_ticks = np.arange(groundtruth_position[1] - tick_range, groundtruth_position[1] + tick_range + 1) # Set the ticks on the plot ax.set_xticks(x_ticks) ax.set_yticks(y_ticks) # --- 新增:强制设置X、Y轴的显示范围 --- ax.set_xlim(-tick_range, tick_range) ax.set_ylim(-tick_range, tick_range) # Ensure the aspect ratio is equal to make the plot square-shaped ax.set_aspect('equal') # Create an ellipse using groundtruth_sigma_x and groundtruth_sigma_y theta = np.linspace(0, 2 * np.pi, 100) x = groundtruth_sigma_x * np.cos(theta) + groundtruth_position[0] y = groundtruth_sigma_y * np.sin(theta) + groundtruth_position[1] ax.plot(x, y) # Display the plot plt.grid(True) plt.show()
关键修改说明
- 添加
ax.set_xlim(-tick_range, tick_range)和ax.set_ylim(-tick_range, tick_range),强制让X、Y轴的显示范围完全一致(都是从-tick_range到tick_range)。 - 配合已有的
ax.set_aspect('equal'),确保绘图区域的宽高比为1:1,最终呈现出标准的方形绘图。
这样修改后,X轴和Y轴的范围会保持一致,当groundtruth_sigma_x和groundtruth_sigma_y相等时,椭圆会正确显示为圆形。
内容的提问来源于stack exchange,提问作者skm
相关产品推荐
相关产品推荐

