Search code examples
pandasaxis-labelssubplotaxes

Pandas Bar Plot and Labels in Subplots


df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
x=[1,2,3,4,5]
y=[1,4,9,16,25]

fig, axes = plt.subplots(figsize=(8,8),nrows=2, ncols=2)
ax1=plt.subplot(2,2,1)
plt.plot(x,y)

#ax2=plt.subplot(2,2,2)
df["b"].plot(ax=axes[0,1], kind='bar', grid=True)
df["c"].plot(ax=axes[1,0], kind='bar', grid=True)
df["d"].plot(ax=axes[1,1], kind='bar', grid=True)

ax1.grid(True)
ax1.set_ylabel('Test')
ax1.set_xlabel('Test2')

#ax2.set_ylabel('Test')

How do I add axes labels for the bar plots in my subplots? Notice I have commented out ax2=plt.subplot(2,2,2) as I was testing this but this erases the bar plot completely and add the labels. Why does it do that and how can I get around this? Below is the output with the ax2... un-commented.

Plot with the lines un-commented


Solution

  • As far as I understand, you do not need ax1 and ax2. You are better off with axes grids:

    fig, axes = plt.subplots(figsize=(8,8),nrows=2, ncols=2)
    axes[0,0].plot(x,y)
    df["b"].plot(ax=axes[0,1], kind='bar', grid=True)
    df["c"].plot(ax=axes[1,0], kind='bar', grid=True)
    df["d"].plot(ax=axes[1,1], kind='bar', grid=True)
    axes[0,0].grid(True)
    axes[0,0].set_ylabel('Test')
    axes[0,0].set_xlabel('Test2')
    axes[0,1].set_ylabel('Test')
    

    Output:

    enter image description here