pythonpandasmatplotlibbar-chartstacked

pandas, matplotlib, drawing a stacked bar chart


I have a dataframe like this:

Names   loc.items
Name1   343 1756
Name2   5   15
Name3   688 1667
Name4   88  444
Name5   1   1
....
Name99  22  111

It is easy to get a stacked bar where the names are on x axis and the stacked bar is on every name.

I want to get it the other way around. I want two stacked bars with 99 stacks(names inside) for location and items. Like the table itself. Each stack pair of a Name(x) has a thickness of loc.(x) and items(x) How can I make this chart?

This:

myclist[[ myclist.loc[:,"names"]]].plot(x='carrier', kind='bar', stacked=True) 

or this approach

# plot data in stack manner of bar type
df.plot(x='Carrier', kind='bar', stacked=True,
        title='Stacked Bar Graph by dataframe')
plt.show()

does not work. If the dataframe look like below, it would work. But written (manually) as series 'location' and 'items' and separate 'columns' it works. I thought it should be the same thing but it seems not so:

df = pd.DataFrame([['location', 10, 20, 10, 26], ['items', 20, 25, 15, 21]],
                  columns=['Names', 'Name1', 'Name2','Name3', 'Name99'])

enter image description here


Solution

  • It is possible, but I think there is many rows, so ouput for 100 rows is not readable:

    df.set_index('Names').T.plot(kind='bar', stacked=True)
    

    pic

    One possible idea is filter names, here between Name1 and Name4:

    df.set_index('Names').loc['Name1':'Name4'].T.plot(kind='bar', stacked=True)