同一画布绘制两个透视表图表时显示异常的问题求助
Hey there, let's break down why your subplots are showing up out of order and with missing data, then fix it step by step!
What's Causing the Problem?
The core issue here is that you're creating subplot objects (gh1, gh2) but not telling pandas' plot() method to use them. By default, pandas will generate a new figure for each plot() call instead of using the subplots you've already set up in your existing figure. This leads to:
- The first
temp1.plot()creates an unseen figure, then yourgh1subplot ends up being empty (but gets rendered later, making it look like the second plot) - The
temp2.plot()creates another new figure, and yourgh2subplot remains empty with no data
Corrected Code
Here's the fixed version where we explicitly link each pandas plot to the corresponding subplot using the ax parameter:
import matplotlib.pyplot as plt # Create the main figure fig = plt.figure(figsize=(8,6)) # First subplot (left) gh1 = fig.add_subplot(121) # Tell pandas to plot onto gh1 temp1.plot(kind='bar', ax=gh1) gh1.set_xlabel('credit_history') gh1.set_ylabel('count of credit history') gh1.set_title('Applicants by credit history') # Second subplot (right) gh2 = fig.add_subplot(122) # Tell pandas to plot onto gh2 temp2.plot(kind='bar', ax=gh2) gh2.set_xlabel('credit_history') gh2.set_ylabel('Probability of loan by credit history') gh2.set_title('Probability of getting loan by credit history') # Optional: Adjust layout to prevent label overlap plt.tight_layout() plt.show()
Key Changes Explained
- Added
ax=gh1totemp1.plot(): This directs pandas to draw the bar chart directly onto the first subplot we created - Added
ax=gh2totemp2.plot(): Same for the second subplot - Added
plt.tight_layout(): Ensures titles and labels don't overlap between subplots (a nice quality-of-life tweak)
With these changes, your subplots will appear in the correct order (left: applicant count, right: loan probability) and both will display their respective data properly.
内容的提问来源于stack exchange,提问作者Abhishek Singh

