【发布时间】:2021-01-22 17:52:46
【问题描述】:
我正在绘制一个分类变量的计数,并想添加第二个 y 轴来显示样本总数的百分比。
import matplotlib.pyplot as plt
import seaborn as sns
titanic = sns.load_dataset("titanic")
g = sns.catplot(x="alive", col="embark_town", col_wrap=4,
data=titanic[titanic.deck.notnull()],
kind="count", height=4, aspect=.8)
for i, ax in enumerate(g.axes.flat):
# Create second y-axis for the percentages on the right
ax1 = ax.twinx()
### Attempt to fix percentages by plotting the bars over
#g = sns.catplot(x="alive", col="embark_town", col_wrap=4,
# data=titanic[titanic.deck.notnull()],
# kind="count", height=4, aspect=.8,
# ax = ax1)
# Label by the percentages
ax1.set_ylim(ax.get_ylim())
ax1.set_yticklabels(np.round(ax.get_yticks()/titanic[titanic.deck.notnull()].shape[0],1))
ax1.set_ylabel('Percentage')
# Rotate x-labels
labels = ax.get_xticklabels() # get x labels
ax.set_xticklabels(labels, rotation=90)
# Ensure good spacing
g.fig.tight_layout()
好的,现在我的问题是百分比在右侧 y 轴上重复,如下图所示
我试图通过在新轴上绘制计数来纠正此问题,但这会添加另一行子图(请参阅 for 循环中注释掉的代码)。如何获得正确的 y 轴标签以不包含重复值并实际反映总数的百分比?
【问题讨论】:
-
您的标签显示为“重复”,因为您将比率四舍五入到小数点后一位(只需将
1更改为3即可查看差异)。也许将它们乘以100,例如像这样:percent = (ax.get_yticks() / titanic[titanic.deck.notnull()].shape[0] * 100).astype('int')和ax1.set_yticklabels(percent)` -
哈哈哈好收获!
标签: python-3.x matplotlib seaborn