from matplotlib import pyplot as plt
from matplotlib.ticker import PercentFormatter
import seaborn as sns
import numpy as np
titanic = sns.load_dataset('titanic')
ax = sns.histplot(data=titanic, x='age', hue='alive', multiple='fill', bins=np.arange(0, 91, 10), palette='spring')
for bars in ax.containers:
heights = [b.get_height() for b in bars]
labels = [f'{h * 100:.1f}%' if h > 0.001 else '' for h in heights]
ax.bar_label(bars, labels=labels, label_type='center')
ax.yaxis.set_major_formatter(PercentFormatter(1))
ax.set_ylabel('Percentage of age group')
plt.tight_layout()
plt.show()
1条答案
按热度按时间disho6za1#
对于seaborn,您可以使用
sns.histplot(..., multiple='fill')
。下面是一个从titanic数据集开始的示例: