1

I would like to plot multiple barplots on a row using the same ax, but it seems that the pandas plot function removes my previous plot everytime.

For example :

import pandas as pd
import pylab as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'lab':['D', 'E', 'F'], 'val':[10, 30, 20]})
df.plot.bar(x='lab', y='val', rot=0, ax=ax)
df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
df.plot.bar(x='lab', y='val', rot=0, ax=ax)
ax.set_xlim(-.5, 6)
plt.show()

Give me

barplot fail

I tried to use the xticks parameter of the pandas function but it didn't work.

jsgounot
  • 709
  • 6
  • 12
  • Possible duplicate of [https://stackoverflow.com/questions/42128467/matplotlib-plot-multiple-columns-of-pandas-data-frame-on-the-bar-chart](https://stackoverflow.com/questions/42128467/matplotlib-plot-multiple-columns-of-pandas-data-frame-on-the-bar-chart)? – m13op22 Feb 21 '19 at 16:02
  • they're plotting over each other. Note the legend in the top. The labels correspond to the second data set. – mauve Feb 21 '19 at 16:04

3 Answers3

0

You need to set up where the bars are on the X axis

https://matplotlib.org/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py

men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)

ind = np.arange(len(men_means))  # the x locations for the groups
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std,
                color='SkyBlue', label='Men')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std,
                color='IndianRed', label='Women')

Note the "ind" section - that's establishing the locations of the bars. Also note that the colors of the bars are spelled out.

mauve
  • 2,707
  • 1
  • 20
  • 34
0

Ok so it looks like I have to provide all ticks every time

fig, ax = plt.subplots()

df = pd.DataFrame({'lab':['A', 'B', 'C', 'D', 'E', 'F'], 'val':[10, 30, 20, 0, 0, 0]})
df.plot.bar(x='lab', y='val', rot=0, ax=ax)
df = pd.DataFrame({'lab':['A', 'B', 'C', 'D', 'E', 'F'], 'val':[0, 0, 0, 10, 30, 20]})
df.plot.bar(x='lab', y='val', rot=0, ax=ax)

plt.show()
jsgounot
  • 709
  • 6
  • 12
0

You would probably want to merge the two dataframes before plotting.

import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
df1 = pd.DataFrame({'lab':['D', 'E', 'F'], 'val':[10, 30, 20]})
df2 = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})

df1.append(df2).plot.bar(x='lab', y='val', rot=0, ax=ax)

plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712