Skip to content Skip to sidebar Skip to footer

Multiple Y-axis With Matplotlib With Twinx

Question: How to apply twinx with Pandas & matplotlib I know that this question has been answered by people multiple times but I just cant get my head around it. Any help will

Solution 1:

Here is how you would do what you are trying to achieve. I create two axes ax1, and ax2 = ax1.twinx(), then I use pandas' plot function to plot a subset of the columns (using y=[<list of columns>]), but the import part is to tell pandas which axes to use when plotting, hence df.plot(..., ax=ax1) and df.plot(..., ax=ax2). The rest of the code is just decorations.

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
df3.plot(x='Year',y='Average Premium', ax=ax1)
df3.plot(x='Year',y=['Mercedes Benz','Nissan','Honda','Toyota','Mazda'], ax=ax2)
ax1.set_title('Comparison of Demand of Car Brand with COE prices ',fontsize = 15)
ax1.set_xlabel('Year',fontsize=12)
ax1.set_ylabel('Average Premium', fontsize=12)
ax2.set_ylabel('2nd axis label',  fontsize=12)
plt.tight_layout()
plt.show()

Post a Comment for "Multiple Y-axis With Matplotlib With Twinx"