使用Pandas合并两个数据图表

4

我已经将数据框df绘制成了堆叠条形图:

dft['Date'] = old['DATE'].dt.to_period('M')
df = dft.groupby(by=['Date', 'Size'])['Spend'].sum()  
stacked = df.unstack('Size').plot(kind='bar', stacked=True)

这个堆叠条形图每月都有一根条。

我有另一个名为 cir 的数据框,其中包含季度数据(每 3 个月一次)。我需要将此数据作为背景覆盖在主堆叠条形图的整个 3 个月上。以下代码可以单独绘制季度数据。

cir['date'] = ['3-15','4-15', '1-16', '2-16', '3-16', '4-16', '1-17', '2- 
17', '3-17', '4-17']
cir['value'] = [78.4, 13.5, 19.8, 19, 78.4, 123.2, 82.6, 86.4, 83.5, 12.2.4]
cir.plot.bar()

我想将这两个图层叠加在一起(它们有不同的y轴)。我尝试使用子图功能,但没有真正取得进展。

你能展示一下你当前的图表吗? - b-fg
1个回答

1

由于您没有提供足够的信息或您编写的代码,因此这更像是伪代码而不是实际代码。但是,这可以为您提供有关如何结合pandas.DataFrame.plotmatplotlib.pyplot.bar以及不同的y轴的一些提示。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

width = 1
fig, ax1 = plt.subplots()
value_x = np.arange(cir['value'])
ax1.bar(x, cir['value'], width = 3*width)
ax2 = ax1.twinx()
df.unstack('Size').plot(kind='bar', stacked=True, ax=ax2, secondary_y=True, width=width)

plt.show()

请注意,诀窍是使用 ax2 = ax1.twinx() 并在不同的轴上绘制您的系列。
关于 width,我不确定这是否有效,因为我不知道您的 x 轴是什么。但这只是为了让您了解如何做到这一点。

谢谢,这些信息应该会非常有帮助。请注意,我现在已经添加了一些关于轴的更多信息。 - William
要添加错误,只需在 ax1.bar(x, cir['value'], width = 3*width, yerr=the_error) 中使用 yerr=the_error - b-fg
你可以在 ax1.bar(x, cir['value'], width = 3*width, alpha=0.5) 中尝试使用 alpha=0.5 或介于0和1之间的其他值。如果有帮助,请考虑接受答案,如果有新问题,请创建新帖子 :) - b-fg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接