尝试使用 Matplotlib 的子图功能时如何停止获取空白图?

How do I stop the getting blank plots when trying to use Matplotlib's subplot feature?

我目前正在撰写一些 Vidhya 文章。作为后续的一部分,我 运行 以下代码:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,4))
ax1 = fig.add_subplot(121)
ax1.set_xlabel('Credit_History')
ax1.set_ylabel('Count of Applicants')
ax1.set_title("Applicants by Credit_History")
temp1.plot(kind='bar')

ax2 = fig.add_subplot(122)
temp2.plot(kind = 'bar')
ax2.set_xlabel('Credit_History')
ax2.set_ylabel('Probability of getting loan')
ax2.set_title("Probability of getting loan by credit history")

这应该会产生以下结果:

Correct answer from Vidhya

这看起来很简单。我明白

然而,当我尝试这样做时,无论我如何摆弄东西,我都会得到这个。

What I'm getting

显然,这是不对的。我对应该发生的事情的理解是:

  1. 我创建了一个图形。
  2. 我指定该图将有两个子图,“121”和“122”指定它们将水平相邻。
  3. 当我使用 'plot' 命令时,子图应该按照它们生成的顺序使用。

不幸的是,我使用的代码似乎只利用了一个子图,然后在新的一行上生成另一个图。我这辈子都弄不明白为什么会这样。

在撰写本文时,我阅读了一些 'Python for Data Analysis' 并尝试了一些新代码但无济于事。我也尝试以这种方式打印它并得到类似的结果:

fig, axes = plt.subplots(1, 2, figsize=(10, 8))
temp1.plot(kind='bar')
temp2.plot(kind='bar')

temp1和temp2的代码如下:

temp1 = df['Credit_History'].value_counts(ascending=True)
temp2 = df.pivot_table(values='Loan_Status',index['Credit_History'],aggfunc=lambda x: x.map({'Y':1,'N':0}).mean())

似乎即使我打印了两次temp1,第一个子图由于某种原因还是空白。我真的很困惑。后者使它工作的尝试几乎是 'Python for Data Analysis' 中代码的精确副本。

您没有在您想要的轴上绘图。您需要告诉 Pandas 您想要哪个轴。

试试这个:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8, 4))
ax1 = fig.add_subplot(121)
ax1.set_xlabel('Credit_History')
ax1.set_ylabel('Count of Applicants')
ax1.set_title("Applicants by Credit_History")
temp1.plot(kind='bar', ax=ax1)

ax2 = fig.add_subplot(122)
ax2.plot(kind='bar')
ax2.set_xlabel('Credit_History')
ax2.set_ylabel('Probability of getting loan')
ax2.set_title("Probability of getting loan by credit history")
temp2.plot(kind='bar', ax=ax2)

注意 plot 方法中的 ax kwarg。