【问题标题】:Two bar plots in one graph from different dataframes (one common column)来自不同数据框的一张图中的两个条形图(一个公共列)
【发布时间】:2019-06-07 08:50:23
【问题描述】:

我有两个简单的数据框

1.

count type
400   customer
1200  subscriber

2.

count type
2000  customer
5000  subscriber

我正在尝试用一个数字制作条形图

X 轴:客户 - 客户,订阅者 - 订阅者 -> 同类型并排)

Y轴:计数

我试过了

df1.plot.bar()
df2.plot.bar()

卡在这里。

【问题讨论】:

    标签: python python-3.x pandas matplotlib


    【解决方案1】:

    你会想merge数据一起:

    combined = df1.merge(df2, on="type", suffixes=["1", "2"]).set_index("type")
    

    然后你可以一键绘制它们:

    combined.plot.bar()
    

    【讨论】:

      【解决方案2】:

      我喜欢另一个优雅的答案。但是,由于您已标记 matplotlib,您可能有兴趣了解相应的解决方案。这里的想法是将条形对齐到主要刻度的边缘,然后使用负宽度和正宽度将它们向左/向右移动。

      P.S:这是一个定制的解决方案,用于绘制相邻的两个条形图。原则上,这可以用于绘制多个条形图。

      import matplotlib.pyplot as plt
      
      plt.bar(df1['type'], df1['count'], align='edge', width=-0.3, label='count1')
      plt.bar(df2['type'], df2['count'], align='edge', width=0.3, label='count2')
      
      plt.legend()
      

      【讨论】:

        猜你喜欢
        • 2020-09-19
        • 2016-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-03
        • 1970-01-01
        • 1970-01-01
        • 2017-07-20
        相关资源
        最近更新 更多