構(gòu)建一個(gè)顯示的數(shù)值的函數(shù)椒振,將plt.pie中的autopct=該函數(shù)即可昭伸。
代碼:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.size'] = 7.0 # matplotlib設(shè)置全局字體
# 創(chuàng)建兩組數(shù)據(jù)
x1 = [30,25, 66, 13, 23]
x2 = [29, 28, 90, 19, 31]
x_0 = [1,0,0,0] #用于顯示空心
labels = ["Intron","Intergenic","UTR","Exon","CDS"] # 標(biāo)簽
colors = ["#FFDD55","#EE7700","#99FF99","#5599FF","#FF77FF"] # 對應(yīng)的顏色
# 用于設(shè)置legend的字體和大小
font1 = {'family' : 'Times New Roman',
'weight' : 'normal',
'size' : 15,
}
# 創(chuàng)建圖片
plt.figure(figsize=(20,20))
fig, ax = plt.subplots()
# 背景色
rect = fig.patch
rect.set_facecolor('white')
# 數(shù)值
def make_autopct(values):
def my_autopct(pct):
total = sum(values)
val = int(round(pct*total/100.0))
# 同時(shí)顯示數(shù)值和占比的餅圖
return '{p:.2f}% ({v:d})'.format(p=pct,v=val)
return my_autopct
#做出三個(gè)pie圖,最后一個(gè)用作中間的空心
pie_1 = ax.pie(x1,startangle = 90,radius=1.8,pctdistance = 0.9,colors=colors,autopct=make_autopct(x1),textprops = {'fontsize':13, 'color':'k'})
pie_2 = ax.pie(x2,startangle = 90,radius=1.3,pctdistance = 0.9,colors=colors,autopct=make_autopct(x2),textprops = {'fontsize':13, 'color':'k'})
pie_0 = ax.pie(x_0, radius=0.8,colors = 'w')
# 設(shè)置圖片標(biāo)題
ax.text(0.1, 2.2, 'test', fontsize=24, style='oblique', ha='center',va='top',wrap=True)
# 畫出每個(gè)pie圖的邊的顏色
for pie_wedge in pie_0[0][:1]:
pie_wedge.set_edgecolor('gray')
for pie_wedge in pie_1[0]:
pie_wedge.set_edgecolor('gray')
for pie_wedge in pie_2[0]:
pie_wedge.set_edgecolor('gray')
# 設(shè)置legend的位置和字體
ax.legend(labels, bbox_to_anchor=(1.3,1.0), loc='center left', prop=font1)
fig.savefig('~/test.png',dpi=200,bbox_inches = 'tight',facecolor=fig.get_facecolor(), transparent=True)
# 將圖設(shè)置為圓形
ax.set(aspect="equal")
plt.show()
生成圖: