【2.5.2】饼形图(Pie Chart)

饼图是显示群组成的经典方式。 然而,现在通常不建议使用它,因为馅饼部分的面积有时会变得误导。 因此,如果您要使用饼图,强烈建议明确记下饼图每个部分的百分比或数字。

# Import
df_raw = pd.read_csv("https://github.com/selva86/datasets/raw/master/mpg_ggplot2.csv")

# Prepare Data
df = df_raw.groupby('class').size()

# Make the plot with pandas
df.plot(kind='pie', subplots=True, figsize=(8, 8), dpi= 80)
plt.title("Pie Chart of Vehicle Class - Bad")
plt.ylabel("")
plt.show()
# Import
df_raw = pd.read_csv("https://github.com/selva86/datasets/raw/master/mpg_ggplot2.csv")

# Prepare Data
df = df_raw.groupby('class').size().reset_index(name='counts')

# Draw Plot
fig, ax = plt.subplots(figsize=(12, 7), subplot_kw=dict(aspect="equal"), dpi= 80)

data = df['counts']
categories = df['class']
explode = [0,0,0,0,0,0.1,0]

def func(pct, allvals):
    absolute = int(pct/100.*np.sum(allvals))
    return "{:.1f}% ({:d} )".format(pct, absolute)

wedges, texts, autotexts = ax.pie(data, 
                                  autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"), 
                                  colors=plt.cm.Dark2.colors,
                                 startangle=140,
                                 explode=explode)

# Decoration
ax.legend(wedges, categories, title="Vehicle Class", loc="center left", bbox_to_anchor=(1, 0, 0.5, 1))
plt.setp(autotexts, size=10, weight=700)
ax.set_title("Class of Vehicles: Pie Chart")
plt.show()

二、我的案例

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np 
one_fp= 'summary/cell_info_merge.xlsx'
df = pd.read_excel(one_fp)

df = df[['barcode','new_clonotype']]
df = df.sort_values(by=['new_clonotype'],ascending=[True])

df['sample'] = df['barcode'].str.split('_',expand=True)[0] + '_' + df['barcode'].str.split('_',expand=True)[1]

df = df[['new_clonotype','sample']]
df = df.groupby(['new_clonotype','sample']).agg({'sample':'count'})
df = df.rename(columns = {'sample':'count'})

df = df.reset_index()

fig, axs = plt.subplots(3,4,figsize=(16,12), subplot_kw=dict(aspect="equal"), dpi= 80)  #equal使饼图长宽相等

def func(pct, allvals):
    absolute = int(pct/100.*np.sum(allvals))
    return "{:.1f}% ({:d} )".format(pct, absolute)

# num = 0
num = 12

for ii in range(3):
    for jj in range(4):
        num+=1
        clono_id = num
        df_new = df[df['new_clonotype']==clono_id]

        data = df_new['count']
        categories = df_new['sample']

#         color_hash = {'M_1':'orange','M_2':'green'} # 自定义颜色
        color_hash = {'M_1':plt.cm.Dark2.colors[0],'M_2':plt.cm.Dark2.colors[1]} # 自定义颜色
        colors =[color_hash[zz] for zz in categories.values]        

        data_size = df_new['count'].sum()
        radius  = np.true_divide(np.log(data_size),3)

        wedges, texts, autotexts = axs[ii,jj].pie(data, autopct=lambda pct: func(pct, data),
                                                  textprops=dict(color="w"), colors=colors,startangle=140,radius=radius)# ,explode=explode)
        axs[ii,jj].set_title("Clonotype%s (%s Abs)" % (clono_id,data_size))
                             
plt.show()

参考资料

个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn