【问题标题】:Why am I getting an extra bar graph in Python?为什么我在 Python 中得到一个额外的条形图?
【发布时间】:2019-08-19 21:47:21
【问题描述】:

我目前在我的 iPython 笔记本中关注 analyticsvidhya.com 上的初学者级贷款预测分类问题。

(https://www.analyticsvidhya.com/blog/2016/01/complete-tutorial-learn-data-science-python-scratch-2/)

我在 Jupyter 上使用内联 Pylab。

到目前为止,我们已经编写了数据透视表和条形图。但是当我尝试绘制 2 个条形图时,我得到 3 个条形图,其中一个为空白。

# pivot table

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())
print ('Frequency Table for Credit History:') 
print (temp1)

# bar graphs

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")

为什么不只返回 2 个条形图?

当我尝试他们的替代方案时:

“另外,这两个图也可以通过将它们组合成堆叠图表来可视化:”

temp3.plot(kind='bar', stacked=True, color=['red','blue'], grid=False)

它像他们的示例一样正确返回一个组合条形图,但之前的 2 个条形图不起作用。

谢谢。

【问题讨论】:

    标签: python pandas matplotlib jupyter-notebook


    【解决方案1】:

    尝试以下操作:在绘制数据框时传递轴对象

    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) # <---- changed
    
    ax2 = fig.add_subplot(122)
    temp2.plot(kind = 'bar', ax=ax2) # <---- changed
    ax2.set_xlabel('Credit_History')
    ax2.set_ylabel('Probability of getting loan')
    ax2.set_title("Probability of getting loan by credit history")
    

    【讨论】:

      猜你喜欢
      • 2013-07-24
      • 1970-01-01
      • 2015-06-20
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 1970-01-01
      相关资源
      最近更新 更多