matplotlib圆环图/饼图显示比值

构建一个显示的数值的函数,将plt.pie中的autopct=该函数即可。

代码:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.size'] = 7.0 # matplotlib设置全局字体

# 创建两组数据
x1 = [30,25, 66, 13, 23]
x2 = [29, 28, 90, 19, 31]

x_0 = [1,0,0,0] #用于显示空心
 
labels = ["Intron","Intergenic","UTR","Exon","CDS"] # 标签
colors = ["#FFDD55","#EE7700","#99FF99","#5599FF","#FF77FF"] # 对应的颜色


# 用于设置legend的字体和大小
font1 = {'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 15,
        }
# 创建图片        
plt.figure(figsize=(20,20))
fig, ax = plt.subplots()

# 背景色
rect = fig.patch
rect.set_facecolor('white')

# 数值
def make_autopct(values):
    def my_autopct(pct):
        total = sum(values)
        val = int(round(pct*total/100.0))
        # 同时显示数值和占比的饼图
        return '{p:.2f}% ({v:d})'.format(p=pct,v=val)
    return my_autopct

#做出三个pie图,最后一个用作中间的空心
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')

# 设置图片标题
ax.text(0.1, 2.2, 'test', fontsize=24, style='oblique', ha='center',va='top',wrap=True)

# 画出每个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')

# 设置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)
# 将图设置为圆形
ax.set(aspect="equal")
plt.show()

生成图:


你可能感兴趣的:(matplotlib圆环图/饼图显示比值)