Matplotlib subplot2grid布局异常求助(核裂变模拟场景)
Let's get your layout sorted out so the simulation plot takes up most of the space, and the power graph sits neatly beside it—while keeping that core boundary rectangle intact.
Modified Code with Working Layout
Here's the adjusted code that addresses the layout problem:
import matplotlib.pyplot as plt import matplotlib.animation as animation BOUNDS = [-20, 20, -20, 20] fig = plt.figure(figsize=(10, 6)) # Set a reasonable overall figure size # Simulation plot: takes up the left 2 rows, 1 column, with equal aspect ratio ax = plt.subplot2grid((2, 2), (0, 0), rowspan=2, colspan=1, aspect='equal', autoscale_on=False, xlim=(-25, 25), ylim=(-25, 25)) # Power plot: takes up the right 2 rows, 1 column ax1 = plt.subplot2grid((2, 2), (0, 1), rowspan=2, colspan=1) ax1.set_xlabel('Time') ax1.set_ylabel('Joules') # Fixed spelling from "Jouls" # Create core boundary rectangle (matches BOUNDS dimensions) rect_width = BOUNDS[1] - BOUNDS[0] rect_height = BOUNDS[3] - BOUNDS[2] rect = plt.Rectangle((BOUNDS[0], BOUNDS[2]), rect_width, rect_height, ec='black', lw=2, fc='none') ax.add_patch(rect) ax.axis('off') plt.tight_layout() # Automatically adjusts spacing to avoid overlaps plt.show()
Why Your Original Layout Broke
Let's break down the issues with your initial code:
Aspect Ratio Constraint Conflict
You setaspect='equal'for the simulation plot, which forces Matplotlib to render the axis as a perfect square. Your originalxlim=(-51.2,51.2)(width 102.4) andylim=(-50.4,50.4)(height 100.8) were almost square but not quite—Matplotlib stretched the axis to enforce the 1:1 ratio, which squeezed the adjacent subplot out of its intended space.Mismatched Axis Range and Rectangle Size
The core boundary rectangle was sized toBOUNDS(40x40), but your axis range was much larger. Combined with theaspect='equal'rule, this made the axis prioritize maintaining a square shape over respecting your subplot grid layout, leading to unexpected spacing.Incorrect Grid Layout Parameters
Your original grid was(3,2), with the simulation plot taking up the first 2 rows across both columns, and the power plot tucked in the bottom-right corner. This wasn't aligned with your goal of having the power plot directly beside the simulation.
Key Fixes in the Modified Code
- Redesigned Grid: Switched to a
(2,2)grid where the simulation plot occupies the entire left column (2 rows), and the power plot takes the entire right column—this creates the side-by-side layout you want. - Aligned Axis Limits: Set
xlimandylimto(-25,25)to give the core rectangle some breathing room while maintaining a perfect square ratio, soaspect='equal'doesn't warp the layout. - Tight Layout: Added
plt.tight_layout()to automatically adjust subplot spacing and prevent overlapping elements.
内容的提问来源于stack exchange,提问作者Omer Hen

