[英]Seaborn: How to scale Y axis to 100 percent for each categorical value
Objective:客观的:
I want to create a stack histogram of a PaperlessBilling
categorical feature (Telco Customer Churn dataset), display the Y axis as a percentage and display the churn distribution as the hue.我想创建一个
PaperlessBilling
分类特征(电信客户流失数据集)的堆栈直方图,将 Y 轴显示为百分比并将流失分布显示为色调。 But, the percentage is not from the accumulative calculation.但是,百分比不是来自累计计算。
Here is what I expected if using R:如果使用 R,这是我所期望的:
ggplot(Churn, aes(SeniorCitizen, fill = Churn)) +
geom_bar(position = "fill") +
xlab("Senior Citizen status") +
ylab("Percent") +
scale_y_continuous(labels = scales::percent) +
scale_x_discrete(labels = c("Non-Senior Citizens", "Senior Citizens")) +
scale_fill_manual(name = "Churn Status", values = c("green2", "red1"), labels = c("No", "Yes")) +
ggtitle("The Ratio of Churns by Senior Citizen status") +
theme_classic() +
theme(legend.position = "bottom",
plot.title = element_text(hjust = 0.5, size = 15))
Here is the output of above code (see that both of the category has total 100%):这是上面代码的output(看到这两个类别的总数都是100%):
Here is what I've done:这是我所做的:
fig, axs = plt.subplots(figsize=(5, 5))
sns.histplot(
df,
x = "PaperlessBilling",
hue = "Churn",
multiple = "stack",
stat = "percent"
)
This is the output of above code:这是上面代码的output:
With stat="percent"
, all bars sum up to 100. To have all bars belonging to the same x-value summing up to 100, you can use multiple='fill'
.使用
stat="percent"
,所有条形的总和为 100。要使属于同一 x 值的所有条形的总和为 100,您可以使用multiple='fill'
。 Note that in the latter case, the sum is 1.0
.请注意,在后一种情况下,总和为
1.0
。 The PercentFormatter
can show the y-axis as percentages. PercentFormatter
可以将 y 轴显示为百分比。
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
import seaborn as sns
import pandas as pd
import numpy as np
df = pd.DataFrame({"PaperlessBilling": np.random.choice(['Yes', 'No'], p=[.6, .4], size=2000)})
df["Churn"] = np.where(df["PaperlessBilling"] == 'Yes',
np.random.choice(['Yes', 'No'], p=[.7, .3], size=2000),
np.random.choice(['Yes', 'No'], p=[.9, .1], size=2000))
df["PaperlessBilling"] = pd.Categorical(df["PaperlessBilling"], ['Yes', 'No']) # fix an order
df["Churn"] = pd.Categorical(df["Churn"], ['Yes', 'No']) # fix an order
palette = {'Yes': 'crimson', 'No': 'limegreen'}
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))
sns.histplot(df, x="PaperlessBilling", hue="Churn", palette=palette, alpha=1,
multiple="stack", stat="percent", ax=ax1)
ax1.yaxis.set_major_formatter(PercentFormatter(100))
sns.histplot(df, x="PaperlessBilling", hue="Churn", palette=palette, alpha=1,
multiple="fill", ax=ax2)
ax2.yaxis.set_major_formatter(PercentFormatter(1))
sns.despine()
plt.tight_layout()
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.