Multiple Y-axis with matplotlib with Twinx

梦想与她 提交于 2021-01-29 08:40:34

问题


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 be greatly appreciated! Basically, I have this code. But I need the x axis to show the years and the secondary y axis to show the demand of the different car brands.

import pandas as pd
import csv
df3=pd.read_csv('comparison.csv'
df3.plot()
plt.legend (loc='best', fontsize=15)
plt.title('Comparison of Demand of Car Brand with COE 
prices ',fontsize = 15)
plt.xlabel('Year',fontsize=12)
plt.ylabel('Average Premium',fontsize=12)
plt.show()

After writing the code into a new file. I will then proceed to read the file and convert it into a line plot with multiple data columns.

What I currently have now is this:
My output

What I want it to look like:
Desired Output

This is my csv file

Year,Average Premium,Mercedes Benz,Nissan,Honda,Toyota,Mazda
2010,22931.0,4705.0,1798.0,3272.0,6927.0,1243.0
2011,35283.0,4166.0,800.0,942.0,3562.0,265.0
2012,48676.0,4705.0,1798.0,3272.0,6927.0,1243.0
2013,54672.0,3871.0,623.0,423.0,3459.0,635.0
2014,49301.0,4651.0,1829.0,1541.0,5431.0,1967.0
2015,47499.0,5408.0,5574.0,7916.0,12171.0,5287.0
2016,39158.0,6444.0,7028.0,19349.0,18491.0,7091.0
2017,37223.0,7976.0,5241.0,16013.0,19133.0,8509.0

I Know that this is the code to do twinx as an example but i need help implementing it

fig, ax1 = plt.subplots()
t = np.arange(2010,2018,1)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
ax1.set_ylabel('rh', color='b')
ax1.tick_params('y', colors='b')

ax2 = ax1.twinx()
s2 = [1,2,4,9,10]
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('tmp', color='r')
ax2.tick_params('y', colors='r')

回答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()


来源:https://stackoverflow.com/questions/52126702/multiple-y-axis-with-matplotlib-with-twinx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!