【问题标题】:How do I stop the getting blank plots when trying to use Matplotlib's subplot feature?尝试使用 Matplotlib 的子图功能时如何停止获取空白图?
【发布时间】:2017-07-07 12:37:07
【问题描述】:

我目前正在撰写一些 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”并尝试了一些新代码,但无济于事。我也尝试过以类似的方式打印它:

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”中代码的精确副本。

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    你没有在你想要的轴上绘图。你需要告诉 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。

    【讨论】:

      猜你喜欢
      • 2012-08-18
      • 2020-01-08
      • 2012-04-19
      • 2023-04-11
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多