美文网首页工作生活
python绘制带有负百分比的饼状图

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

作者: Aerosols | 来源:发表于2019-07-04 20:01 被阅读0次

matplotlib
饼状图:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.pie.html
保存图片:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.savefig.html
subplot_adjust:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html

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

相关文章

网友评论

    本文标题:python绘制带有负百分比的饼状图

    本文链接:https://www.haomeiwen.com/subject/mckdhctx.html