首页 > 解决方案 > 百分比堆积条 - 在 Python Pandas 中实现百分比时出现语法错误?

问题描述

我有如下数据框:

import io
import matplotlib.pyplot as plt

df = pd.read_csv(io.StringIO("""target   |product
1        |EHZ
1        |GBK
0        |EHZ
0        |AKP
1        |AKP"""), sep="\s+\|", engine="python")

我需要在百分比堆积图上显示上述数据,如下所示:

在此处输入图像描述

为此,我尝试使用以下代码:

fig, ax = plt.subplots(figsize=(10,3))

# prepare dataframe for plotting
dfp = pd.crosstab(index=df["product"], columns=df["target"]).apply(lambda r: r/r.sum(), axis=1)
# simple stacked plot
ax = dfp.plot(kind="barh", stacked=True, ax=ax)

for c in ax.containers:
    # customize the label to account for cases when there might not be a bar section
    labels = [f'{w*100:.0f}%' if (w := v.get_width()) > 0 else '' for v in c ]
    
    # set the bar label
    ax.bar_label(c, labels=labels, label_type='center')
        
ax.set_xlabel("procent")
ax.set_title("tytul")

但我有如下语法错误:

在此处输入图像描述

你能帮我把这段代码重写为 Python 3.7.4 版吗?由于此语法错误是由 Python 版本引起的(上面的代码仅适用于 Python 3.8 或更高版本)或寻找其他解决方案(其他代码)如何在 Python 中创建如上图所示的绘图?

非常感谢!

标签: pythonpandasmatplotlibplot

解决方案


推荐阅读