这是一种使用pandas的方法:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
def label_function(val):
return f'{val / 100 * len(df):.0f}\n{val:.0f}%'
N = 50
df = pd.DataFrame({'country': np.random.choice(['UK', 'US', 'NZ'], N),
'gender': np.random.choice(['Male', 'Female'], N)})
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5))
df.groupby('country').size().plot(kind='pie', autopct=label_function, textprops={'fontsize': 20},
colors=['tomato', 'gold', 'skyblue'], ax=ax1)
df.groupby('gender').size().plot(kind='pie', autopct=label_function, textprops={'fontsize': 20},
colors=['violet', 'lime'], ax=ax2)
ax1.set_ylabel('Per country', size=22)
ax2.set_ylabel('Per gender', size=22)plt.tight_layout()
plt.show()
PS:要只显示百分比,请使用autopct='%1.0f%%'。