You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pandas饼图中使用DataFrame指定值自定义数据标签

自定义预设百分比标签的饼图实现方案

pandas 的饼图绘制底层调用 matplotlib 接口,我们可以通过自定义 autopct 参数,替换默认自动计算的占比标签,直接使用 DataFrame 中预先存储的 exposure 列数值作为标签。

你原有代码存在两处笔误:

  • y 参数传入的列名是 "market value",和实际定义的列名 market_value 不一致
  • figsize(8,8) 写法错误,正确传参格式为 figsize=(8,8)

可运行参考代码

import pandas as pd
import matplotlib.pyplot as plt

# 构造测试数据
chart = pd.DataFrame(
    {"market_value": [229500, 261377, 341155], "exposure": [0.007648, 0.008712, 0.011372]},
    index = ["Large", "Mid", "Small"]
)

# 预先格式化好要展示的自定义百分比标签
custom_pct = [f"{val*100:.2f}%" for val in chart["exposure"]]

# 绘制饼图,autopct传入自定义标签逻辑
ax = chart.plot.pie(
    title = "Exposure by Market Cap",
    y = "market_value",
    figsize = (8,8),
    autopct = lambda x: custom_pct.pop(0)
)

# 保证饼图为正圆形
ax.axis("equal")
plt.show()

上述代码中autopct参数传入的lambda函数会依次读取提前格式化好的自定义百分比标签,完全替换默认计算的占比数值,实现和Excel一致的效果。

内容的提问来源于stack exchange,提问作者MindyKornfeld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 00:06:02