rocksNwaves
rocksNwaves

Reputation: 6164

Subplots not populating correctly

I am trying to use Pandas DataFrame.plot() to plot two variable bar plots side by side with the following code:

fig, (ax1, ax2) = plt.subplots(1,2)
ax1 = train_df['Condition1'].value_counts().plot(kind='bar')
ax2 = train_df['Condition2'].value_counts().plot(kind='bar')
plt.show()

The result is this:

enter image description here

The data is Kaggle's House Prices dataset, however I do not think it matters to answering the question. I have tried this with multiple pairs of variables just to be sure. It only ever shows one plot on the right.

Interestingly enough, the assignment of axes does not matter. If you only assign ax1, it will show in the right hand plot. If you only assign ax2, it will be on the right side.

This occurs no matter what orientation I choose for my subplots (2,) (1,2), (2,1). Always one empty plot.

What's going on here?

Upvotes: 2

Views: 486

Answers (1)

petezurich
petezurich

Reputation: 10214

You already created the axes with your first line of code. Your second and third code line overwrite these.

You need to pass ax1 and ax2 as arguments to pandas' plot function instead.

Try this:

fig, (ax1, ax2) = plt.subplots(1,2)
train_df['Condition1'].value_counts().plot(kind='bar', ax=ax1)
train_df['Condition2'].value_counts().plot(kind='bar', ax=ax2)
plt.show()

enter image description here

Upvotes: 2

Related Questions