正如评论中已经提到的那样,最好的方法可能是在绘制之前进行操作。这是一种方法:
import pandas as pdfrom matplotlib import pyplot as pltimport numpy as npcountries = [ 'Albania', 'Brazil', 'Denmark', 'France', 'Mexico', 'Nigeria', 'Spain', 'Germany', 'Finland', ]#the full dataframedf = pd.Dataframe( data = {'country': countries, 'value' :np.random.rand(len(countries))}, ).sort_values('value', ascending = False)#the top 5df2 = df[:5].copy()#othersnew_row = pd.Dataframe(data = { 'country' : ['others'], 'value' : [df['value'][5:].sum()]})#combining top 5 with othersdf2 = pd.concat([df2, new_row])#plotting -- for comparison left all countries and right #the others combinedfig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (9,4))df.plot(kind = 'pie', y = 'value', labels = df['country'], ax = axes[0])df2.plot(kind = 'pie', y = 'value', labels = df2['country'], ax = axes[1])axes[0].set_title('all countries')axes[1].set_title('top 5')plt.show()结果看起来像这样。
希望这可以帮助。



