0

I have a dataframe such as this:

data = {'name': ['Bob', 'Chuck', 'Daren', 'Elisa'],
        '100m': [19, 14, 12, 11],
        '200m': [36, 25, 24, 24],
        '400m': [67, 64, 58, 57],
        '800m': [117, 120, 123, 121]}

df = pd.DataFrame(data)

     name   100m    200m   400m   800m
1     Bob     19      36     67    117
2   Chuck     14      25     64    120
3   Daren     12      24     58    123
4   Elisa     11      24     57    121

My task is simple: Plot the times (along the y-axis), with the name of the event (100m, 200m, etc. along the x-axis). The hue of each bar should be determined by the 'name' column, and look something like this.

column names as x-axis

Furthermore, I would like to overlay the results (not stack). However, there is no functionality in seaborn nor matplotlib to do this.

You_Donut
  • 155
  • 8
  • Note that on StackOverflow you are supposed to add some minimal reproducible code to your question. – JohanC Nov 17 '22 at 19:11

1 Answers1

2

Instead of using seaborn, which is an API for matplotlib, plot df directly with pandas.DataFrame.plot. matplotlib is the default plotting backend for pandas.

Tested in python 3.11, pandas 1.5.1, matplotlib 3.6.2, seaborn 0.12.1

ax = df.set_index('name').T.plot.bar(alpha=.7, rot=0, stacked=True)

enter image description here

seaborn.barplot does not have an option for stacked bars, however, this can be implemented with seaborn.histplot, as shown in Stacked Bar Chart with Centered Labels.

df must be converted from a wide format to a long format with df.melt

# melt the dataframe
dfm = df.melt(id_vars='name')

# plot
ax = sns.histplot(data=dfm, x='variable', weights='value', hue='name', discrete=True, multiple='stack')

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
  • Is there any way to have the stacked bars overlap? If the bars would additionally have lowered opacity (for visibility), it would then prevent from the values exploding and generating really tall bars for some cases. – You_Donut Nov 18 '22 at 12:46
  • Is there a way not to stack the bars? Basically, to have the bars of each person for that column next to each other - as in OP's post? – Nick Jul 22 '23 at 09:27
  • 1
    @Nick like this `df.set_index('name').T.plot.bar()` ? – Scott Boston Jul 22 '23 at 09:29