如何在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
相关产品推荐
相关产品推荐

