簡體   English   中英

Seaborn:如何將每個分類值的 Y 軸縮放為 100%

[英]Seaborn: How to scale Y axis to 100 percent for each categorical value

客觀的:

我想創建一個PaperlessBilling分類特征(電信客戶流失數據集)的堆棧直方圖,將 Y 軸顯示為百分比並將流失分布顯示為色調。 但是,百分比不是來自累計計算。

如果使用 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))

這是上面代碼的output(看到這兩個類別的總數都是100%):

在此處輸入圖像描述

這是我所做的:

fig, axs = plt.subplots(figsize=(5, 5))

sns.histplot(
    df,
    x = "PaperlessBilling",
    hue = "Churn",
    multiple = "stack",
    stat = "percent"
)

這是上面代碼的output:

在此處輸入圖像描述

使用stat="percent" ,所有條形的總和為 100。要使屬於同一 x 值的所有條形的總和為 100,您可以使用multiple='fill' 請注意,在后一種情況下,總和為1.0 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()

sns.histplot stat="percent" vs multiple="fill"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM