Matplotlib调用subplot()方法后首个子图未显示的问题排查
Let's break down exactly what's happening here—this issue is definitely caused by the order of your code calls and how Matplotlib manages its axes objects, not missing parameters.
What's Going Wrong Step-by-Step
Your first plot lands on the default axes
When you runplt.plot(np.log(df['Total Cases']), np.log(df['Active']), 'go'), Matplotlib automatically creates a new figure and a single "default" axes that takes up the entire figure. This plot is drawn here, but you never interact with this axes again after this line.Subplots overwrite the current axes context
Next,plt.subplot(1,3,1)creates the first subplot in a 1-row, 3-column grid. This becomes the "active" axes, so your next plot (the blue star for discharged cases) draws here. Thenplt.subplot(1,3,2)switches to the second subplot, and your deaths plot gets drawn there.Third subplot is created but unused
plt.subplot(1,3,3)creates the third empty subplot, but you don’t plot anything on it. Meanwhile, that initial default axes (with your active cases plot) gets hidden under the subplot grid, so it never shows up in your final output.
That’s why you’re seeing the discharged and deaths plots in the first two subplot slots, the third is empty, and your original active cases plot is nowhere to be found.
How to Fix It
You have two straightforward, clean ways to resolve this:
Option 1: Use the state-based plt interface correctly
Switch to each subplot before plotting on it, so every plot targets the right axes:
# Switch to first subplot, then plot plt.subplot(1,3,1) plt.plot(np.log(df['Total Cases']), np.log(df['Active']), 'go') # Switch to second subplot, then plot plt.subplot(1,3,2) plt.plot(np.log(df['Total Cases']), np.log(df['Discharged']), 'b*') # Switch to third subplot, then plot plt.subplot(1,3,3) plt.plot(np.log(df['Total Cases']), np.log(df['Deaths']), 'go') plt.tight_layout() plt.show()
Option 2: Object-oriented approach (recommended for subplots)
Create the figure and all subplots at once, then plot directly on each explicit axes object—this eliminates confusion about which axes you’re targeting:
# Create figure and 3 subplots in one line fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 4)) # Adjust size as needed # Plot on each specific axes ax1.plot(np.log(df['Total Cases']), np.log(df['Active']), 'go') ax2.plot(np.log(df['Total Cases']), np.log(df['Discharged']), 'b*') ax3.plot(np.log(df['Total Cases']), np.log(df['Deaths']), 'go') plt.tight_layout() plt.show()
Key Takeaway
Matplotlib’s state-based plt functions always act on the "current" axes. If you plot before creating subplots, that plot ends up on a separate axes that gets covered when you add the subplot grid to the same figure. Always make sure you’re targeting the right axes—either by switching to it with subplot before plotting, or using the explicit object-oriented axes handles.
内容的提问来源于stack exchange,提问作者AvikumarT

