带有Matxlotlib和Twinx的多个Y轴 [英] Multiple Y-axis with matplotlib with Twinx
问题描述
问题:如何在 Pandas & 中应用 twinxmatplotlib
Question: How to apply twinx with Pandas & matplotlib
我知道人们已经多次回答了这个问题,但我就是无法理解.任何帮助将不胜感激!基本上,我有这段代码.但我需要 x 轴来显示年份,第二个 y 轴来显示不同汽车品牌的需求.
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:
我想要的样子:
What I want it to look like:
这是我的 csv 文件
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
我知道这是做twinx的代码,但是我需要帮助实现它
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')
推荐答案
这是您将要实现的目标.我创建两个轴 ax1
和 ax2 = ax1.twinx()
,然后使用pandas的 plot
函数绘制列的子集(使用 y = [<列列表>]
),但是导入部分是告诉熊猫在绘制时要使用哪些轴,因此 df.plot(...,ax =ax1)
和 df.plot(...,ax = ax2)
.其余代码只是装饰.
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()
这篇关于带有Matxlotlib和Twinx的多个Y轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!