如何解决Matplotlib子图高度递减问题,保持每行子图高度恒定?
Got it, let's resolve that frustrating subplot height issue you're seeing. The root cause is how your current code sets up the subplot grid in each iteration—here's the breakdown and two straightforward solutions:
Why Your Subplots Are Shrinking
For each store at index i, you're using plt.subplot(str(index+1),2,1) which creates a grid with i+1 rows. Since you call plt.show() after each store, the second store's figure has 2 rows (but you only use the first row), the third has 3 rows, and so on. The default figure height stays the same, so each row (and your subplots) get progressively shorter as the number of rows increases.
Solution 1: Separate Figure Per Store (Fixed Height)
If you want each store's ACF/PACF pair in its own consistent-sized figure, use a 1-row grid every time and explicitly set a fixed figure size:
from statsmodels.graphics.tsaplots import plot_pacf, plot_acf import matplotlib.pyplot as plt import numpy as np from statsmodels.tsa.stattools import acf, pacf for index, store in enumerate(StoreData): print('\033[1m PACF AND ACF for Store:', store, '\033[0m') sales_data = StoreData[store]['Sales'] lag_acf = acf(sales_data, nlags=20) lag_pacf = pacf(sales_data, nlags=20, method='ols') conf_int = 1.96 / np.sqrt(len(sales_data)) # Reuse this value for clean code # Create a new figure with fixed dimensions (adjust width/height as needed) plt.figure(figsize=(10, 5)) # Plot PACF (1 row, 2 columns, first subplot) plt.subplot(1, 2, 1) plt.plot(lag_pacf) plt.axhline(y=0, linestyle='--', color='gray') plt.axhline(y=-conf_int, linestyle='--', color='gray') plt.axhline(y=conf_int, linestyle='--', color='gray') plt.title('Partial Autocorrelation Function') # Plot ACF (1 row, 2 columns, second subplot) plt.subplot(1, 2, 2) plt.plot(lag_acf) plt.axhline(y=0, linestyle='--', color='gray') plt.axhline(y=-conf_int, linestyle='--', color='gray') plt.axhline(y=conf_int, linestyle='--', color='gray') plt.title('Autocorrelation Function') plt.tight_layout() # Prevent overlapping labels/titles plt.show()
Key fixes:
plt.figure(figsize=(10,5))ensures every figure has the same height- Replaced
str(index+1)with1to use a single row per store's plot pair - Calculated the confidence interval once to avoid redundant code
Solution 2: All Stores in One Figure (Uniform Row Heights)
If you prefer all plots in a single unified figure, create a grid with len(StoreData) rows upfront. This guarantees every row has identical height:
from statsmodels.graphics.tsaplots import plot_pacf, plot_acf import matplotlib.pyplot as plt import numpy as np from statsmodels.tsa.stattools import acf, pacf num_stores = len(StoreData) # Create a grid of axes: num_stores rows, 2 columns fig, axes = plt.subplots(num_stores, 2, figsize=(10, 4*num_stores)) # Height scales with store count for index, store in enumerate(StoreData): print('\033[1m PACF AND ACF for Store:', store, '\033[0m') sales_data = StoreData[store]['Sales'] lag_acf = acf(sales_data, nlags=20) lag_pacf = pacf(sales_data, nlags=20, method='ols') conf_int = 1.96 / np.sqrt(len(sales_data)) # Plot PACF on the left axis of the current row ax_pacf = axes[index, 0] ax_pacf.plot(lag_pacf) ax_pacf.axhline(y=0, linestyle='--', color='gray') ax_pacf.axhline(y=-conf_int, linestyle='--', color='gray') ax_pacf.axhline(y=conf_int, linestyle='--', color='gray') ax_pacf.set_title(f'PACF - Store {store}') # Plot ACF on the right axis of the current row ax_acf = axes[index, 1] ax_acf.plot(lag_acf) ax_acf.axhline(y=0, linestyle='--', color='gray') ax_acf.axhline(y=-conf_int, linestyle='--', color='gray') ax_acf.axhline(y=conf_int, linestyle='--', color='gray') ax_acf.set_title(f'ACF - Store {store}') plt.tight_layout() plt.show()
Key improvements:
plt.subplots(num_stores, 2)creates all axes at once, ensuring uniform row heights- The figure height is set to
4*num_storesso each row gets ~4 inches of space (adjust this value to your liking) - Directly access axes from the
axesarray for cleaner, more efficient code
Pick whichever solution fits your visualization needs—both will eliminate the decreasing subplot height issue!
内容的提问来源于stack exchange,提问作者Aniket

