When creating a histogram plot with seaborn, I would like to dynamically put the bar with the lower count to the front. Below is a minimal example where now the blue bar is always in the front, no matter its count. For example, in the second bin, I would like the orange bar to be in the front. Basically, I am looking for something similar to multiple="stack"
, however without adding the columns up. Is that possible?
import numpy as np
import pandas as pd
import seaborn as sns
sns.set()
df_A = pd.DataFrame(np.random.randint(0, 10, 100), columns=["value"])
df_A["label"] = "A"
df_B = pd.DataFrame(np.random.randint(0, 10, 100), columns=["value"])
df_B["label"] = "B"
df = pd.concat([df_A, df_B])
sns.histplot(df, x="value", bins=np.arange(0, 10, 1), hue="label")
You could loop through the generated bar containers and compare the heights of corresponding bars. The order of the heights can then be used to set their z-order. Optionally, you could set
alpha=1
to make them opaque.Here is an example with more hue values.
np.argsort
needs to be called twice to get the inverse order.Here is how it would look like for matplotlib histograms (all created using the same bins):