Search code examples
pythonplotseabornhistogram

Seaborn histplot stacked bar not stacking as expected in Python


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


Solution

  • 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: