python - 百分比堆积条 - 在 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 中创建如上图所示的绘图?
非常感谢!
解决方案
推荐阅读
- powershell - -match 比较器的问题
- sql - 'ORA-00904: "RIGHT": invalid identifier' Oracle 查询错误
- php - WordPress 主题 wp_enqueue_style() 上传后不起作用
- python - 根据条件向文件添加行
- python - 为什么直播推文时会有延迟?
- c# - 修复 iTextSharp 的错误(PDF 到文本)?
- testing - 如何使用 React Hooks 测试库测试 useEffect 中的回调调用
- python - 加快读取和操作 30,000 个 csv 文件
- python-3.x - 0-1 背包问题 Python:为什么我们返回最大值
- php - 如果给定键的值匹配,则将一个数组元素添加到另一个数组中