如何在PyCharm的Jupyter Notebook中调整Pyplot图表尺寸
Hey there! I’ve dealt with this exact headache in PyCharm’s integrated Jupyter environment before—adjusting matplotlib figure sizes and watching the plot vanish is so frustrating. Let’s go through targeted fixes that work specifically for PyCharm’s setup:
1. Explicitly Define Figure Size + Use plt.show() (Critical for PyCharm)
The most common culprit here is missing a proper plt.show() call or misordering your code. In PyCharm’s Jupyter, you need to explicitly create your sized figure first, plot, then trigger display:
import matplotlib.pyplot as plt # Step 1: Create a figure with your desired dimensions (width, height in inches) plt.figure(figsize=(10, 6)) # Step 2: Plot your data as usual plt.plot([1, 3, 5], [2, 7, 3]) plt.xlabel("X Axis") plt.ylabel("Y Axis") plt.title("Resized Plot in PyCharm Jupyter") # Step 3: Force the plot to display—this is often missing when plots vanish plt.show()
Pro tip: Avoid calling plt.figure() after plotting, as this can create an empty figure and hide your actual plot.
2. Set Global Default Figure Size
If you want all your plots to use a consistent size without repeating figsize every time, update matplotlib’s global configuration:
import matplotlib.pyplot as plt # Set default figure dimensions for all subsequent plots plt.rcParams['figure.figsize'] = (12, 8) # Now any plot you create will automatically use this size plt.scatter([4, 2, 6], [5, 1, 8]) plt.show()
This saves you from manually setting figsize for every single plot.
3. Adjust Matplotlib Backend (If Other Fixes Fail)
Sometimes PyCharm’s default matplotlib backend can cause display glitches when resizing. Try switching to a different backend before importing pyplot:
import matplotlib # Switch to a backend that plays nicely with PyCharm (try TkAgg or Qt5Agg) matplotlib.use('TkAgg') import matplotlib.pyplot as plt plt.figure(figsize=(9, 5)) plt.bar(['Apple', 'Banana', 'Cherry'], [15, 22, 18]) plt.show()
Note: Make sure you have the required backend libraries installed (e.g., python3-tk for TkAgg on Linux).
Quick Troubleshooting Checks
- Don’t mix
%matplotlib inlineandplt.show(): Using both can cause conflicts in PyCharm. Pick one—inline embeds plots in the cell, whileplt.show()opens a resizable window. - Double-check for accidental
plt.close()calls: If your code closes the figure before displaying it, the plot will disappear.
内容的提问来源于stack exchange,提问作者Evan Maltz




