[英]Plotting 2 pie charts side by side in MatPlotLib
我目前正在嘗試在 Matplotlib 中創建 2 個餅圖。 雖然目前我的代碼允許我打印出 2 個餅圖,但它們是在垂直方向打印出來的。 有什么方法可以讓餅圖水平並排打印?
這是我當前的代碼,只允許我垂直打印 2 個餅圖:
import matplotlib.pyplot as plt
import numpy as np
#read the csv file
filename = '../LAB03-DATA VISUALIZATION USING MATPLOTLIB/singapore-residents-by-ethnic-group-and-sex-end-june-annual.csv'
data = np.genfromtxt(filename, dtype=['i8','U50','i8'], delimiter=',', names=True)
#extract datas that are of 1960
data_1960 = data[data['year'] == 1960]
#extract datas that are of 2016
data_2016 = data[data['year'] == 2016]
#extract datas that have this keyword 'TOTAL MALE RESIDENTS' and 'TOTAL FEMALE RESIDENTS'(1960)
male_and_female_1960 = data_1960[np.isin(data_1960['level_1'], ['Total Male Residents' , 'Total Female Residents'])]
#extract datas that have this keyword 'TOTAL MALE RESIDENTS' and 'TOTAL FEMALE RESIDENTS'(2016)
male_and_female_2016 = data_2016[np.isin(data_2016['level_1'], ['Total Male Residents' , 'Total Female Residents'])]
# PLOTTING OF THE 1960 PIE CHART-------------------------------------------------------------------------------------------------
labels = male_and_female_1960['level_1']
values = male_and_female_1960['value']
#settings and configs for the pie charts
colors = ['#FF8F33','#33FFDC']
explode = (0.1, 0)
plt.figure(figsize=(5,5))
plt.pie(values,labels = labels,colors = colors,autopct = '%1.1f%%')
plt.title('Gender Composition in 1960')
# PLOTTING OF THE 2016 PIE CHART-------------------------------------------------------------------------------------------------
labels = male_and_female_2016['level_1']
values = male_and_female_2016['value']
#settings and configs for the pie charts
colors = ['#FF8F33','#33FFDC']
explode = (0.1, 0)
plt.figure(figsize=(5,5))
plt.pie(values,labels = labels,colors = colors,autopct = '%1.1f%%')
plt.title('Gender Composition in 2016')
plt.show()
我目前的 output。
是的你可以 -
fig, (ax1,ax2) = plt.subplots(1,2,figsize=(10,10)) #ax1,ax2 refer to your two pies
# 1,2 denotes 1 row, 2 columns - if you want to stack vertically, it would be 2,1
labels = male_and_female_1960['level_1']
values = male_and_female_1960['value']
ax1.pie(values,labels = labels,colors = colors,autopct = '%1.1f%%') #plot first pie
ax1.title('Gender Composition in 1960')
labels = male_and_female_2016['level_1']
values = male_and_female_2016['value']
ax2.pie(values,labels = labels,colors = colors,autopct = '%1.1f%%') #plot second pie
ax2.title('Gender Composition in 2016')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.