如何在同一张图上绘制两个 DataFrame 进行比较

How to plot two DataFrame on same graph for comparison

我有两个数据框(trail1 和 trail2),其中包含以下列:流派、城市和销售数量。现在我想创建两个数据集的条形图,用于并排比较流派与总销售数量。对于每种类型,我想要两个小节:一个代表小道 1,另一个代表小道 2。

如何使用 Pandas 实现此目的?

我尝试了以下方法,但没有用。

gf1 = df1.groupby(['Genre'])
gf2 = df2.groupby(['Genre']) 
gf1Plot = gf1.sum().unstack().plot(kind='bar, stacked=False)
gf2Plot = gf2.sum().unstack().plot(kind='bar, ax=gf1Plot, stacked=False)

我希望能够看到 trail1 数据集与 trial2 数据相比,每种类型(例如:辣、甜、酸等)的情况如何

我也尝试过使用 concat,但我不知道如何在同一个图表上绘制串联的 DataFrame 来比较两个键。

DF = pd.concat([df1,df2],keys=['trail1','trail2'])

你是一个正确的轨道,但你想要 merge 而不是 concat。试试这个:

DF = pd.merge(df1,df2,on=['Genre','City'])
DF.Groupby([['Genre','City']]).sum().unstack().plot(kind = 'bar')

我找到了问题的解决方案。我欢迎其他人 post 更好的方法。

解法:

df1 = pd.DataFrame(myData1, columns=['Genre', 'City', 'Sold'])
df2 = pd.DataFrame(myData2, columns=['Genre', 'City', 'Sold'])

df1['Key'] = 'trail1'
df2['Key'] = 'trail2'

DF = pd.concat([df1,df2],keys=['trail1','trail2'])

DFGroup = DF.groupby(['Genre','Key'])

DFGPlot = DFGroup.sum().unstack('Key').plot(kind='bar')

这里是生成图的一个例子: