Skip to content Skip to sidebar Skip to footer

Create A Plot From A Pandas Dataframe Pivot Table

I'm new to python and was wondering how to create a barplot on this data I created using pivot table function. #Create a pivot table for handicaps count calculation for no-show peo

Solution 1:

Starting with data_pv, reshape the data into a wide form, with pandas.Dataframe.pivot or pandas.DataFrame.pivot_table, that's easier to plot with pandas.DataFrame.plot, which will use the index as the x-axis, and the columns as the bar values.

  • pivot_table if values need to be aggregated (e.g. 'sum')
  • pivot if no aggregation is needed

Use kind='bar' for a bar plot, or kind='line' for a line plot. Either will work, depending on the desired plot.

df = data_pv.pivot(index='category', columns='gender', values='no_show_prop')

df now looks like:

gender                F          M
category                          
alcoholism    25.18397417.267197
diabetes      18.14127717.672229
hipertension  17.32185917.254720

Then you can simply do:

df.plot(kind='bar')

enter image description here

Solution 2:

This can be done with the dataframe in a long form using seaborn, which makes it very easy to make a categorized barplot, without the need to transform the dataframe to a wide format.

import seaborn as sns

sns.barplot(x='category', y='no_show_prop', hue='gender', data=df)

enter image description here

Post a Comment for "Create A Plot From A Pandas Dataframe Pivot Table"