Hi I'd like to add quantile and mean lines to seaborn histogram subplots.
Example data:
import seaborn as sns
from matplotlib import pyplot as plt
penguins = sns.load_dataset("penguins")
penguins.dropna(inplace=True)
fig, axes = plt.subplots(2, 2, figsize=(20, 7))
plot_data = penguins[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']]
for col, ax in zip(plot_data, axes.flat):
print(col, ax)
sns.histplot(ax=ax, data=plot_data, x=plot_data[col], hue=penguins['sex'], multiple='stack')
To add a quantile line to a single subplot: axes[0,0].axvline(plot_data['bill_length_mm'].quantile(0.25), 0, 1, color='red', ls='--')
I'd like add 0.25, 0.5, 0.75 quantiles and mean to each subplot.
I tried this but it doesn't work
quantiles = [0.25, 0.5, 0.75]
colors = ['green', 'red', 'blue']
l = []
for col in plot_data.columns:
for q, c in zip(quantiles, colors):
l.append([col, q, plot_data.loc[:,col].quantile(q), c])
for l_, ax in zip(l, axes):
ax.axvline(l_[2], 0, 1, color=l[3], ls='--')
Draw a vertical line by getting 25%, 50%, and 75% from the statistics of the data to be drawn, respectively. Kindly refer to this .
import seaborn as sns
from matplotlib import pyplot as plt
penguins = sns.load_dataset("penguins")
penguins.dropna(inplace=True)
fig, axes = plt.subplots(2, 2, figsize=(20, 7))
plot_data = penguins[['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm', 'body_mass_g']]
quantiles = ['25%','50%', '75%']
colors = ['green', 'red', 'blue']
for col, ax in zip(plot_data, axes.flat):
# print(col, ax)
sns.histplot(ax=ax, data=plot_data, x=plot_data[col], hue=penguins['sex'], multiple='stack')
desc = plot_data[col].describe()
# print(desc)
for i in range(len(quantiles)):
ax.axvline(desc[quantiles[i]], color=colors[i])
You were so close. You just had to repeat the working axvline
solution in each subplot for each quantile-color combination. And you rightly thought that zipping them is a way to achieve this. Sticking as closely as possible to your attempt:
...
sns.histplot(ax=ax, data=plot_data, x=plot_data[col], hue=penguins['sex'], multiple='stack')
for q, c in zip(quantiles, colors):
ax.axvline(plot_data[col].quantile(q), 0, 1, color=c, ls='--')
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.