You_Donut
You_Donut

Reputation: 155

seaborn - how to graph a list of list of ints with labels

I currently have a dataframe which looks like this:

     name  class           scores
1     Bob  history     [13, 14, 11]
2   Chuck  math        [12,  7,  8]
3   Daren  history     [26, 14,  9]
4   Elisa  english     [ 8, 14, 10]
5   Aaron  history     [12, 13, 23]
6     Tom  math        [ 7,  7, 28]
7     Dan  history     [13,  2, 13]
8    Fred  english     [ 4,  1,  2]

And I would like to graph this dataframe with the x-axis being scores, the y-axis being the count of scores, and the label (or hue) to be determined by class. Ultimately, it would look similar to this plot (code from https://seaborn.pydata.org/generated/seaborn.histplot.html)

penguins = sns.load_dataset("penguins")
sns.histplot(penguins, x="flipper_length_mm", hue="species", element="step")

stacked histplot with label

where count would be the count of scores, flipper_length_mm would be the value of each score, and species would be class.

I have been trying all sorts of method with zippings and list flattenings but I can't seem to get anything to work. Any help is appreciated!

Upvotes: 1

Views: 483

Answers (1)

Nuri Taş
Nuri Taş

Reputation: 3845

explode scores column so that you can count each different element, and don't forget to set ignore_index=True:

df2 = df.explode('scores', ignore_index=True)
sns.histplot(df2, x="scores", hue="class", element='step')

Result:

enter image description here

Upvotes: 3

Related Questions