Nikli
Nikli

Reputation: 127

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

I am currently working on some Vidhya articles. As part of following along, I'm running the following code:

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

This is supposed to produce the following:

Correct answer from Vidhya

This seems straightforward enough. I understand the

However, when I attempt this, I have been getting this no matter how much I jiggle around with things.

What I'm getting

Obviously, this isn't right. My understanding of what is supposed to happen is:

  1. I create a figure.
  2. I specify that the figure will have two subplots, with the '121' and '122' specifying they will be horizontally adjacent to each other.
  3. As I use the 'plot' command, the subplots should be utilized in the order they were generated.

Unfortunately, it seems like the code I am using is only utilizing ONE of the subplots, and then producing the other plot on a new line. I can not for the life of me figure out why this is the case.

While writing this I read some of 'Python for Data Analysis' and tried some new code to no avail. I've also attempted to print it this way with similar results:

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

The code for temp1 and temp2 are as follows:

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

It seems that even if I print temp1 twice, the first subplot is blank for some reason. I'm really pretty stumped. The latter attempt to make it work is almost an exact copy of the code from 'Python for Data Analysis'.

Upvotes: 1

Views: 2894

Answers (1)

Batman
Batman

Reputation: 8917

You're not plotting in the axis that you want to. You need to tell Pandas which axis you want.

Try this:

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)

Notice the ax kwarg in the plot methods.

Upvotes: 2

Related Questions