3

I have a histplot that is not doing what I am expecting, and I'm unsure why. In my histplot, I want a stacked chart comparing wins by black_first_move, but instead of stacked bars, I'm getting the chart in the image below (and the palette's not being applied). Can anyone provide guidance on how to correctly stack this?

color=['white', 'lightgrey', 'black']
black_fmr_summary_low.head(2)

sns.histplot(
    data=black_fmr_summary_low, multiple="stack",
    x="black_first_move", y="wins", hue="winner",
    palette=color) # color = ['black', 'white', 'gray'] but is not applying
plt.show()

Image of Jupyter Notebook

tdy
  • 36,675
  • 19
  • 86
  • 83
Justin123
  • 57
  • 5

1 Answers1

3

The issue is that histograms aggregate uncounted data, but you've already counted the wins.

Generally bar plots make more sense for counted data, but it seems that the simplest way to make a stacked bar chart in seaborn is via histplot with the weights param:

weights (vector or key in data): If provided, weight the contribution of the corresponding data points towards the count in each bin by these factors.

sns.histplot(
    data=df,
    multiple="stack",
    x="black_first_move",
    weights="wins",  # not y="wins"
    hue="winner",
    palette=color)

Output with some minimal random data:

tdy
  • 36,675
  • 19
  • 86
  • 83
  • 1
    Thank you, this fixed my stacking! Is there a way to specify I want a percent stacked chart though? I wasn't able to find anything in the histplot references, but I'd imagine there must be a way... or do I need to do this manually via the dataframe, and then create the chart? – Justin123 Dec 03 '21 at 14:33
  • 1
    For reference, I've tried adding in stat="percent" but that does not change the bars to be full-length (I want percent by column, not percent by total graph). – Justin123 Dec 03 '21 at 14:39
  • @Justin123 Unfortunately I don't know how to do that in seaborn. I think the only way is to calculate it manually in the dataframe and use pandas `...plot.bar(stacked=True)` – tdy Dec 04 '21 at 08:59
  • I guess that becomes a different problem, maybe something like [How to plot stacked & normalized histograms?](https://stackoverflow.com/q/43074199/13138364) or [How do I make pandas catagorical stacked bar chart scale to 100%](https://stackoverflow.com/q/56251848/13138364) – tdy Dec 04 '21 at 09:01