Greg Rosen
Greg Rosen

Reputation: 197

Why am I getting an extra bar graph in Python?

I'm currently following along in my iPython notebook on a beginner-level Loan Prediction classification problem on analyticsvidhya.com.

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

I'm using inline Pylab on Jupyter.

So far we've coded a pivot table and bar graphs. But when I try to plot the 2 bar graphs, I get 3 bar graphs with one of them blank.

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

Why isn't this returning only 2 bar graphs?

When I try their alternative:

"Alternately, these two plots can also be visualized by combining them in a stacked chart:"

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

it returns one combined bar chart correctly as in their example, but the 2 bar graphs before that don't work.

Thanks.

Upvotes: 1

Views: 141

Answers (1)

Sheldore
Sheldore

Reputation: 39072

Try the following: pass the axis objects while plotting dataframes

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

Upvotes: 1

Related Questions