Home > other >  pandas, matplotlib, drawing a stacked bar chart
pandas, matplotlib, drawing a stacked bar chart

Time:12-17

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'])

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)

CodePudding user response:

import pandas as pd
import matplotlib.pyplot as plt

# Create a dataframe with the original data
df = pd.DataFrame({'Names': ['Name1', 'Name2', 'Name3', 'Name4', 'Name5', ..., 'Name99'],
                   'loc': [343, 5, 688, 88, 1, ..., 22],
                   'items': [1756, 15, 1667, 444, 1, ..., 111]})

# Reshape the dataframe to have columns for each name and rows for location and items
df_stacked = df.set_index('Names').stack().reset_index()
df_stacked.columns = ['Names', 'Type', 'Value']

# Plot the stacked bar chart
df_stacked.plot(x='Names', y='Value', kind='bar', stacked=True, title='Stacked Bar Chart')
plt.show()
  • Related