饼图如何在图表旁标注百分比?附示例数据及目标效果参考
带旁注百分比的饼图实现方案
直接使用matplotlib库即可实现需求,完整可运行代码如下:
import matplotlib.pyplot as plt # 原始数据 users = [80, 40, 1000, 300, 50, 80, 10] os = ['MacOS', 'Chrome', 'Windows', 'Linux', 'Devian', 'Ubuntu', 'Arch Linux'] # 计算各系统用户占比 total_users = sum(users) legend_items = [f"{os[i]}: {(users[i]/total_users)*100:.1f}%" for i in range(len(os))] # 绘制饼图 fig, ax = plt.subplots(figsize=(9, 6)) # 若不需要空心环形效果,删除wedgeprops参数即可得到实心饼图 wedges, _ = ax.pie(users, startangle=90, wedgeprops={"width": 0.3}) # 添加带百分比的图例,放置在饼图右侧 ax.legend(wedges, legend_items, loc="center left", bbox_to_anchor=(1, 0.5)) # 保证饼图为正圆形 ax.axis("equal") plt.show()
效果说明
运行代码后会生成饼图,右侧图例中每个系统名称后直接标注对应占比,和预期展示效果一致。你可以根据需要调整figsize参数修改画布大小,调整bbox_to_anchor参数修改图例的位置。
内容的提问来源于stack exchange,提问作者fiona
相关产品推荐
相关产品推荐

