簡體   English   中英

如何 label 堆疊條 plot 的每個條占總值的百分比?

[英]How to label each bar of a stacked bar plot with percentage of total values?

我正在嘗試 plot 堆疊條形圖 plot,我在其中繪制了我的數據,如下圖所示。 標簽是每個容器的確切值。 我想把這些放在每個 bar 的總值的百分比值中。 到目前為止,我沒有這樣做。 您的幫助將不勝感激。

這是標簽的代碼:

for i, rect in enumerate(ax.patches):
    # Find where everything is located
    height = rect.get_height()
    width = rect.get_width()
    x = rect.get_x()
    y = rect.get_y()
    label_text = f"{height:.02f}"

    label_x = x + width / 2
    label_y = y + height / 2
    ax.text(
        label_x,
        label_y,
        label_text,
        ha="center",
        va="center",
        fontsize=4,
        weight="bold",
    )

在此處輸入圖像描述

給定以下玩具 dataframe:

import pandas as pd
from matplotlib import pyplot as plt

df = pd.DataFrame(
    {
        "A": {2019: 125, 2020: 124, 2021: 50, 2022: 63},
        "B": {2019: 129, 2020: 40, 2021: 85, 2022: 47},
        "C": {2019: 126, 2020: 95, 2021: 51, 2022: 44},
        "D": {2019: 99, 2020: 120, 2021: 106, 2022: 117,},
    }
)
print(df)
# Output
        A    B    C    D
2019  125  129  126   99
2020  124   40   95  120
2021   50   85   51  106
2022   63   47   44  117

這是一種方法:

# Setup figure
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(7, 4))

# Add bars
ax.bar(df.index, df["A"], label="A")
ax.bar(df.index, df["B"], bottom=df["A"], label="B")
ax.bar(df.index, df["C"], bottom=df["A"] + df["B"], label="C")
ax.bar(df.index, df["D"], bottom=df["A"] + df["B"] + df["C"], label="D")

# Add percentages as labels
for idx in df.index:
    start = 0
    for col in df.columns:
        y = df.loc[idx, col]
        value = df.loc[idx, col]
        total = df.loc[idx, :].sum()
        ax.text(
            x=idx,
            y=start + y / 2,
            s=f"{round(100 * value / total, 1)}%",
            fontsize=10,
            ha="center",
            color="w",
        )
        start += y

# Add other useful informations
plt.xticks(df.index, df.index)
ax.legend()

plt.show()

哪些輸出:

在此處輸入圖像描述

暫無
暫無

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

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