Python Matplotlib:如何用变量值创建饼图

1 投票
1 回答
2485 浏览
提问于 2025-04-20 18:35

我现在有一个可以生成饼图的程序,代码大概是这样的:

import matplotlib.pyplot as plt

def get_name_counts(Names):
    if "Bob" in Names:
        NameList[0] +=1
    elif "Ann" in Names:
        NameList[1] +=1
    elif "Ron" in Names:
        NameList[2] +=1
    elif "Zee" in Names:
        NameList[3] +=1

def plot_dist(Values, Labels, Title):
    plt.title(Title)
    plt.pie(Values, labels = Labels, autopct='%0.0f%%', colors = ('g', 'r', 'y',  'c'))

NameList = [0]*4

for Line in File:
    for Names in Line:
        get_name_count(Names)

pp=PdfPages("myPDF.pdf")
MyPlot = plt.figure(1, figsize=(5,5))
Labels = ('Bob', 'Ann', 'Exon', 'Ron', 'Zee')
Values = NameList

plot_dist(Values, Labels, "Name Distribution")
pp.savefig()
plt.close()
pp.close()

不过,我有好几个不同的列表想要生成饼图,我在想有没有更简单的方法来做到这一点。比如说,我不想每次都要指定每个饼图的具体名称,能不能写一个函数,让它自动识别每个独特的名称,并计算相关的数量呢?

1 个回答

1

你可以对列表进行循环,并使用一个计数器来生成唯一的图片文件名:

#!/usr/bin/python3

from matplotlib import pyplot as plt

data = [range(n) for n in range(4,9)]

for i, x in enumerate(data):

    fig = plt.figure()
    ax = fig.add_subplot(111)

    ax.pie(x, labels=x)

    fig.savefig("pie{0}.png".format(i))

这样可以绘制出data的第一层元素,总共会有5个饼图。

撰写回答