一张图中来自不同数据框的两个条形图(一个公共列)

时间:2019-06-07 08:50:23

标签: python python-3.x pandas matplotlib

我有两个简单的数据帧

1。

count type
400   customer
1200  subscriber

2。

count type
2000  customer
5000  subscriber

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

X轴 :客户-客户,订户-订户->彼此相邻的相同类型)

Y轴 :计数

我尝试过

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

并停留在这里。

2 个答案:

答案 0 :(得分:2)

您将需要merge一起数据:

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

然后您可以一次调用将它们绘制出来:

combined.plot.bar()

答案 1 :(得分:1)

我喜欢另一个优雅的答案。但是,由于您已经标记了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()

enter image description here

相关问题