我试图在python的同一函数中创建两个饼图,但是当我尝试这样做时,饼图似乎重叠了,种族饼图的数据仍保留在性别饼图中。
我从数据库中获取饼图数据。
代码:
import matplotlib.pyplot as plt
# Create Pie Chart Of Ethnicitys
# Defining Labels For Pie Chart
Labels = ["White: English", "White: Welsh", "White: Scottish", "White: Northern Irish", "White: British",
"White: Irish", "White: Gypsy", "White: Other", "White and Black: Caribbean", "White and Black: African",
"White and Asain", "Indian", "Pakistani", "Bangladeshi", "Chinese", "African", "Caribbean", "Arab",
"Other"]
# Defining Data Variables For Each Slice Of The Pie Chart
Slices = [NoOfWE, NoOfWW, NoOfWS, NoOfWNI, NoOfWB, NoOfWI, NoOfWG, NoOfWO, NoOfWBC, NoOfWBA, NoOfWA, NoOfI, NoOfP,
NoOfB, NoOfC, NoOfA, NoOfCA, NoOfCAR, NoOfAR, NoOfO]
#Omitted method of getting data for ethnicities.
Cols = ['g', 'y', 'c', 'm', 'r', 'b']
# Plot
plt.pie(Slices, labels=Labels, colors=Cols,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
plt.title("Ethnicity Scouts")
EPieChart = plt.gcf()
pylab.savefig("EthnicityPieChart.png", bbox_inches='tight')
EPieChart.savefig("EthnicityPieChart.png", bbox_inches='tight')
doc.add_picture('EthnicityPieChart.png', width=Inches(4.0))
doc.save("ScoutCensus.docx")
print("Completed")
#Gender Pie Chart
# Defining Labels For Pie Chart
LabelsG = ["Male","Female","Other"]
# Defining Data Variables For Each Slice Of The Pie Chart
NoOfMale=0
NoOfFemale=0
NoOfOther=0
Male=("Male")
Female=("Female")
Other=("Other")
Slices = [NoOfMale,NoOfFemale,NoOfOther]
GetMalesSQL="SELECT COUNT(*) FROM scoutinfo WHERE gender=%s"
mycursor.execute(GetMalesSQL,(Male,))
myresults=mycursor.fetchone()
print("Count result")
print(myresults)
NoOfMale=myresults[0]
GetFemaleSQL="SELECT COUNT(*) FROM scoutinfo WHERE gender=%s"
mycursor.execute(GetMalesSQL,(Female,))
myresults=mycursor.fetchone()
print("Count result")
print(myresults)
NoOfFemale=myresults[0]
GetOtherSQL="SELECT COUNT(*) FROM scoutinfo WHERE gender=%s"
mycursor.execute(GetMalesSQL,(Other,))
myresults=mycursor.fetchone()
print("Count result")
print(myresults)
NoOfOther=myresults[0]
if NoOfMale==0:
Slices.remove(NoOfMale)
LabelsG.remove("Male")
if NoOfFemale==0:
Slices.remove(NoOfFemale)
LabelsG.remove("Female")
if NoOfOther==0:
Slices.remove(NoOfOther)
LabelsG.remove("Other")
# Create Pie Chart Of Gender
Cols = ['b','r','g']
# Plot
plt.pie(Slices, labels=LabelsG, colors=Cols,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
plt.title("Gender Diversity Of Scouts")
GPieChart = plt.gcf()
pylab.savefig("GenderPieChart.png", bbox_inches='tight')
GPieChart.savefig("GenderPieChart.png", bbox_inches='tight')
doc.add_picture('GenderPieChart.png', width=Inches(4.0))
doc.save("ScoutCensus.docx")
print("Completed")
代码: 预期结果:
通常使用它们自己的数据创建饼图。
实际结果: