【2.5.2】饼形图（Pie Chart）

# Import

# 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

# 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 = 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()

wedges, texts, autotexts = axs[ii,jj].pie(data, autopct=lambda pct: func(pct, data),