【问题标题】:How to plot two DataFrame on same graph for comparison如何在同一图表上绘制两个 DataFrame 以进行比较
【发布时间】:2015-09-24 07:48:11
【问题描述】:

我有两个 DataFrame(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'])

【问题讨论】:

    标签: python pandas matplotlib graph data-analysis


    【解决方案1】:

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

    解决方案:

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

    以下是生成图的示例:

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 这个解决方案对我不起作用。我只需要按流派或城市分组;不是都。在我的条形图上,我想为每种类型设置两个条:一个代表数据集 1,另一个代表数据集 2。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多