aquantum
aquantum

Reputation: 177

Two bar plots in one graph from different dataframes (one common column)

I have two simple data frames

1.

count type
400   customer
1200  subscriber

2.

count type
2000  customer
5000  subscriber

I am trying to make bar plot with one figure.

X axis: customer - customer, subscriber - subscriber -> same type next to each other)

Y axis: count

I tried

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

and stuck here.

Upvotes: 2

Views: 1639

Answers (2)

Sheldore
Sheldore

Reputation: 39042

I like the other elegant answer. However, since you have tagged matplotlib, you might be interested in knowing a corresponding solution. The idea here is to align the bars to the edges of major ticks and then use negative and positive width to shift them left/right.

P.S: This is a tailored solution for plotting two bars adjacently. In principle, this can be made general to plot multiple bars.

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

Upvotes: 1

w-m
w-m

Reputation: 11232

You will want to merge the data together:

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

Then you can plot them with one call:

combined.plot.bar()

Upvotes: 2

Related Questions