Subplots for Dataframe.plot.bar

Hi there,

I am currently in the “Guided Project: Visualizing Earnings Based On College Majors” of the Data Scientist in Python path.

I tried to combine subplots with Dataframe.plot.bar but it does not seem to work, as it always prints two empty subplots and then the two separate plots below.

This is my code

fig= plt.figure(figsize=(5,5))
ax1 = fig.add_subplot(2,2,1)
ax1 = recent_grads[:10].plot.bar(x="Major",y="Women")
ax2 = fig.add_subplot(2,2,2)
ax2 = recent_grads[-10:].plot.bar(x="Major",y="Women")

Any suggestions?

Thanks in advance!

fig= plt.figure(figsize=(5,5))
ax1 = fig.add_subplot(2,2,1)
recent_grads[:10].plot.bar(x="Major",y="Women",ax=ax1)
ax2 = fig.add_subplot(2,2,2)
recent_grads[-10:].plot.bar(x="Major",y="Women",ax=ax2)

You probably mean to do this. Whenever you create a variable, make sure you know why you are creating it. In this case, why do you need to assign to ax1, ax2? Also, it looks like you are trying to have 2 plots here, why do 2x2 subplot rather than 1x2 or 2x1?

Why the dataframe plots appear below the figure?
Because you created a 2x2 figure in the 1st step already. It doesn’t matter when you add the subplots in, that visual space is taken so dataframe plots go below.
Try this to see i mess it up

recent_grads[:10].plot.bar(x="Major",y="Women")
fig= plt.figure(figsize=(5,5))
recent_grads[-10:].plot.bar(x="Major",y="Women")
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)

If you don’t give a particular figure or axes to dataframe plotting, it will create a new one for itself. The developers of matplotlib (pandas developers just add some extra layer of API on matplotlib) have to make this new figure and new axes for the convenience of users who are never going to create them before plotting. Here is how to view a list of created figures list(map(plt.figure, plt.get_fignums()))

1 Like