Python Matplotlib:如何创建具有可变值的饼图
我目前有一个工作程序,可以创建类似于下面类似代码的饼图:Python Matplotlib:如何创建具有可变值的饼图,python,matplotlib,charts,Python,Matplotlib,Charts,我目前有一个工作程序,可以创建类似于下面类似代码的饼图: 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"
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()
然而,我有几个不同的列表,我想为它们创建饼图,我想知道是否有更简单的方法来实现这一点。不必为每个图表指定确切的名称,我可以创建一个函数来检测每个唯一的名称并获取相关的计数吗?您可以在列表上运行循环,并保留一个计数器以具有唯一的图像文件名:
#!/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))
这将绘制数据的第一级元素,总共5个饼图