Home > Net >  matplotlib - plot merged dataframe with group bar
matplotlib - plot merged dataframe with group bar

Time:11-10

I try to plot a grouped bar chart from a merged dataframe. below code the bar is stacked, how can I put it side by side just like a grouped bar chart?

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)
df1 = pd.DataFrame({
    'key':  ['A', 'B', 'C', 'D'],
    'value':[ 10  ,6,   6,   8]})
df2 = pd.DataFrame({
    'key':  ['B', 'D', 'A', 'F'],
    'value':[ 3,   5,   5,  7]})

df3 = pd.merge(df1, df2, how='inner', on=['key'])
print(df1)
print(df2)
print(df3)

fig, ax = plt.subplots(figsize=(12, 8))

b1 = ax.bar(df3['key'],df3['value_x'])
b2 = ax.bar(df3['key'],df3['value_y'])

pngname = "demo.png"
fig.savefig(pngname, dpi=fig.dpi)
print("[[./%s]]"%(pngname))

Current output: enter image description here

CodePudding user response:

The problem is that the x axis data is the same, in your case it aren't numbers, it are the keys: "A", "B", "C". So matplotlib stacks them one onto another.

There's a simple way around it, as some tutorials online show Result of running the code from above.

  • Related