I have created two axes in a figure using matplotlib and tried to plot data. One method worked and one did not. My question: why did it not work and what's the difference between the two?
The one which didn't work:
fig,ax=plt.subplots(2,figsize=(15,6))
ax[0]=df['Global_Sales'].head(10).plot(kind='bar')
ax[0].set_xlabel('different games')
ax[0].set_ylabel('Sales')
ax[1]=df['Critic_Score'].head(10).plot(kind='bar')
ax[1].set_xlabel('different games')
ax[1].set_ylabel('Critic Score')
plt.tight_layout()
plt.show()
Here the first axes remains blank and the second axes gets overwritten
The one which did work:
fig,ax=plt.subplots(2,figsize=(15,6))
df['Global_Sales'].head(10).plot(kind='bar',ax=ax[0])
ax[0].set_xlabel('different games')
ax[0].set_ylabel('Sales')
df['Critic_Score'].head(10).plot(kind='bar',ax=ax[1])
ax[1].set_xlabel('different games')
ax[1].set_ylabel('Critic Score')
plt.tight_layout()
plt.show()
showed both the graphs on both axes properly.
Your first example did not produce the output you were expecting because you did not pass the axes objects that you generated using the plt.subplots
call to the pandas .plot
call. Your second example produced the output you were expecting becuase you did pass the axes objects that you generated using the plt.subplots
call to the pandas .plot
call.
In short, if you want a pandas .plot
call to plot on a particular axis (say ax1
), you need to pass that axis object into the .plot
call as a keyword argument: df.plot(ax=ax1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.