python饼图百分比_python绘制带有负百分比的饼状图

本文介绍了如何使用Python的matplotlib库绘制带有负百分比的饼状图。通过enumerate()函数处理数据,并定义自定义函数func2来计算负数百分比。示例代码展示了如何创建一个包含正负数值的饼图,并展示每个部分的百分比。
摘要由CSDN通过智能技术生成

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

语法:

enumerate(sequence, [start=0])

参数:

sequence -- 一个序列、迭代器或其他支持迭代对象。

start -- 下标起始位置。

返回值:

返回 enumerate(枚举) 对象。

https://www.runoob.com/python/python-func-enumerate.html

import numpy as np

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(6, 3), subplot_kw=dict(aspect="equal"))

recipe = ["flour","sugar","butter","berries"]

ingredients = [x.split()[0] for x in recipe]

##pct是pie函数根据给定的一组数(全为正值)计算的百分比,

##allvals是取过绝对值的值,plist是原始带有负值的序列

def func2(pct, allvals, plist):

tsum = np.sum(allvals) ##求和

spct = pct*tsum/100 ###计算具体数值

for i, val in enumerate(allvals):

print(i,val,spct)

if abs(spct - val) < 1.e-4:

index = i

if plist[index] <0 :

spct = spct*(-1)

print(index,spct)

return "{:.1f}%".format(spct)

plist = [ 50, -30.01, 30.02, 40 ]

pabs = [ abs(x) for x in plist ]

wedges, texts, autotexts = ax.pie(pabs, autopct=lambda x: func2(x, pabs, plist),

textprops=dict(color="w"))

ax.legend(wedges, ingredients,

title="Ingredients",

loc="center left",

bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=8, weight="bold")

ax.set_title("Matplotlib bakery: A pie")

plt.show()

test.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值