You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同一画布绘制两个透视表图表时显示异常的问题求助

Fixing Matplotlib Subplot Order & Missing Data Issues

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 your gh1 subplot ends up being empty (but gets rendered later, making it look like the second plot)
  • The temp2.plot() creates another new figure, and your gh2 subplot 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=gh1 to temp1.plot(): This directs pandas to draw the bar chart directly onto the first subplot we created
  • Added ax=gh2 to temp2.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:20:08