结合缺少x值的图

时间:2018-12-27 11:48:39

标签: python pandas dataframe plot

这可能是重复的,但是我找不到解决方案,所以就去了:

我正在尝试将以下数据框组合到一个图中。 Df1:

quarter   count
2017-1    1
2017-2    1
2017-3    1
2017-4    2
2018-2    5
2018-3    2

使用Df2:

quarter   count
2017-1    9
2017-2    16
2017-3    6
2017-4    15
2018-1    14
2018-2    17
2018-3    20
2018-4    16

但是,如果我运行以下命令:

ax = plt.gca()
Df1.plot(x = 'quarter', y = 'count', ax = ax)
Df2.plot(x = 'quarter', y = 'count', ax = ax)
plt.xticks(Df2.index, Df2['quarter'].values)

出现错误,因为它只是在'2018-1'和'2018-2'位置绘制了Df1的'2018-2'和'2018-3'值。我猜这是因为Df1没有'2018-1'值。任何想法如何解决这个问题? (并且让Df1的图在2018-1只是零吗?)

1 个答案:

答案 0 :(得分:2)

使用reindex_likefillna

df1 = df1.set_index('quarter').reindex_like(df2.set_index('quarter')).reset_index().fillna(0)

ax = plt.gca()
df1.plot(x = 'quarter', y = 'count', ax = ax)
df2.plot(x = 'quarter', y = 'count', ax = ax)
plt.xticks(df2.index, df2['quarter'].values)
plt.show()

输出图如下:

enter image description here