如何在matplotlib绘制的饼图中仅展示占比排名前10的热门地点
解决方法
直接在频次统计结果后截取前10项再绘图即可,修改后代码如下:
plt.figure(figsize=(12,10)) # 取热度排名前10的地点 top10_places = df['Places'].value_counts().head(10) top10_places.plot.pie(autopct="%1.1f%%") plt.ylabel('Popular places', size = 20) plt.title('Top 10 Most Popular places in my city by %', size = 20) plt.show()
如果希望总占比显示为100%,可以把其余地点合并为「其他」类别一同展示,实现代码如下:
import pandas as pd plt.figure(figsize=(12,10)) all_place_counts = df['Places'].value_counts() top10 = all_place_counts.head(10) # 统计剩余地点的总频次 others_count = pd.Series([all_place_counts[10:].sum()], index=['其他']) # 合并两组数据 plot_data = pd.concat([top10, others_count]) plot_data.plot.pie(autopct="%1.1f%%") plt.ylabel('Popular places', size = 20) plt.title('Top 10 Most Popular places in my city by %', size = 20) plt.show()
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

