Python Matplotlib: how to create a pie chart with variable values

Question:

I currently have a working program that creates pie charts similar to the similar code below:

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()

However, I have several different lists for which I would like to create pie charts and I was wondering if there is a simpler way to do this. Rather than having to specify the exact names for each chart can I make one function that will detect each unique name and get the associated count?

Asked By: user2165857

||

Answers:

You can run a loop over the lists, and keep a counter to have a unique image file name:

#!/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))

This plots first-level elements of data, 5 pie charts overall.

Answered By: Adobe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.