X轴比例尺与同一绘图上的2个数据集不匹配

时间:2019-04-27 17:38:06

标签: python matplotlib

我有2个试图在同一图上绘制的数据集。它们共享一个我在X轴上使用的共同列,但是我的一组数据是每年收集的,而另一组是每月收集的,因此每组中的数据点的数量明显不同。

Pyplot不会在我将两个集合绘制在同一张图上的情况下绘制每个集合的X值

仅绘制每年收集的数据集时,我得到: Tax Data

仅绘制每月收集的数据集时,我得到: Trip Data

但是当我绘制覆盖的两个集合(下面的代码)时,我得到了: Both Data

tframe:

   10003   Date
0    257 201401
1    216 201402
2    417 201403
3    568 201404
4    768 201405
5    836 201406
6    798 201407
7    809 201408
8    839 201409
9    796 201410

tax_for_zip_data:

TAX BRACKET $1 under $25,000    ...       Date
2                       5740    ...     201301
0                       5380    ...     201401
1                       5320    ...     201501
3                       5030    ...     201601

因此,我按照wwii的建议进行了操作,并将Date列转换为datetime对象:

tframe:

   10003       Date
0    257 2014-01-31
1    216 2014-02-28
2    417 2014-03-31
3    568 2014-04-30
4    768 2014-05-31
5    836 2014-06-30
6    798 2014-07-31
7    809 2014-08-31
8    839 2014-09-30
9    796 2014-10-31

tax_for_zip_data:

TAX BRACKET $1 under $25,000    ...           Date
2                       5740    ...     2013-01-31
0                       5380    ...     2014-01-31
1                       5320    ...     2015-01-31
3                       5030    ...     2016-01-31

但是日期仍在绘制偏移量, Both Data

我的数据最早都不能追溯到2012年-2013年1月。 tax_for_zip_data全部抵消了一年。如果我仅绘制该图集,则可以正确绘制。 Tax Data

fig, ax1 = plt.subplots(sharex = True)

color = "tab:red"
ax1.set_xlabel('Date')
ax1.set_ylabel('Trips', color = color)
tframe.plot(kind = 'line',x = 'Date', y = "10003", ax = ax1, color = color)
ax1.tick_params(axis = 'y', labelcolor = color)


ax2 = ax1.twinx()
color = "tab:blue"
ax2.set_ylabel('Num Returns', color = color)
tax_for_zip_data.plot(kind = 'line', x = 'Date', y = tax_for_zip_data.columns[:-1], ax = ax2)
ax2.tick_params(axis = 'y', labelcolor = color)

plt.show()

1 个答案:

答案 0 :(得分:1)

如果可以使DataFrame索引成为日期时间索引,则绘制起来会更容易。

s = '''10003   Date
257   201401
216   201402
417   201403
568   201404
768   201405
836   201406
798   201407
809   201408
839   201409
796   201410
'''
df1 = pd.read_csv(io.StringIO(s), delimiter='\s{2,}',engine='python')
df1.index = pd.to_datetime(df1['Date'],format='%Y%m')

s = '''TAX BRACKET     $1 under $25,000           Date
2                       5740         201301
0                       5380         201401
1                       5320         201501
3                       5030         201601
'''
df2 = pd.read_csv(io.StringIO(s), delimiter='\s{2,}',engine='python')
df2.index = pd.to_datetime(df2['Date'],format='%Y%m')

您无需为plot的{​​{1}}参数指定参数。

x

enter image description here