Jupyter Notebook中plt.figure()的figsize设置不生效求助
Hey there! I’ve dealt with this frustrating issue a bunch of times in Jupyter, so let’s walk through the most common fixes that should get your figure sizes behaving as expected.
1. Make sure you create the figure before plotting
This is the #1 mistake I see! If you plot your data first and then try to set figsize, you’re actually creating a new, blank figure instead of modifying the one with your plot.
Wrong way:
import matplotlib.pyplot as plt # Oops, plotting first then creating figure plt.plot([1, 2, 3, 4]) plt.figure(figsize=(10, 6)) # This makes a new empty figure plt.show()
Correct way:
import matplotlib.pyplot as plt # Create the figure with your desired size first plt.figure(figsize=(10, 6)) plt.plot([1, 2, 3, 4]) plt.show()
2. Use plt.subplots() instead (more reliable)
I’ve found using the subplots() function to create both your figure and axes object directly is way more consistent, especially in Jupyter. It explicitly ties your plot to the figure with the size you set:
import matplotlib.pyplot as plt # Create figure and axes with specified size fig, ax = plt.subplots(figsize=(12, 5)) ax.plot([1, 3, 2, 4]) # Plot directly on the axes plt.show()
3. Reset old figures or set global defaults
If you’ve been running multiple plot cells in your notebook, leftover figure instances might be messing things up. Close all existing figures first before creating a new one:
plt.close('all') # Clear all previous figures plt.figure(figsize=(8, 4)) plt.plot([1, 5, 3, 7]) plt.show()
Or set a global default size so every new figure uses it automatically:
import matplotlib.pyplot as plt # Set default figsize for all future plots plt.rcParams['figure.figsize'] = (10, 6) # Now any plot will use this size by default plt.plot([2, 4, 6, 8]) plt.show()
4. Check your Jupyter matplotlib backend
Rarely, the backend Jupyter uses to display plots can cause sizing quirks. If the above fixes don’t work, try switching your backend at the top of your notebook:
%matplotlib inline # This is the default, but sometimes reloading helps # Or try interactive backend: %matplotlib notebook
Give these steps a shot—9 times out of 10, it’s just a matter of ordering your code correctly or using subplots() instead of plt.figure() alone.
内容的提问来源于stack exchange,提问作者zesla

