【问题标题】:Multiple Y-axis with matplotlib with Twinx使用带有 Twinx 的 matplotlib 的多个 Y 轴
【发布时间】:2019-02-07 03:36:28
【问题描述】:

问题:如何在 Pandas 和 matplotlib 中应用 twinx

我知道人们已经多次回答了这个问题,但我就是想不通。任何帮助将不胜感激!基本上,我有这个代码。但是我需要 x 轴来显示年份和次要 y 轴来显示不同汽车品牌的需求。

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

将代码写入新文件后。然后我将继续读取文件并将其转换为具有多个数据列的线图。

我现在拥有的是这个:

我希望它是什么样子:

这是我的 csv 文件

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 为例的代码,但我需要帮助来实现它

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')

【问题讨论】:

  • 每个轴上应该绘制什么?在左侧,Average PremiumYear,在右侧 y 轴上,各种 brands 与 Year?对吗?
  • 是的,没错!

标签: python-3.x matplotlib plot yaxis


【解决方案1】:

以下是您将如何实现您想要实现的目标。 我创建了两个轴ax1ax2 = ax1.twinx(),然后我使用pandas 的plot 函数来绘制列的子集(使用y=[<list of columns>]),但导入部分是告诉pandas 在绘图时使用哪些轴,因此df.plot(..., ax=ax1)df.plot(..., ax=ax2)。其余的代码只是装饰。

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

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多