将小于x%的字典值合并到单个其他扇区饼图中
你好,我有一个数据字典,如下所示:
pDict = {'"Streptococcous targeted"': 678000 , '"s.coccous file read"': 6780 , '"Mycobacterium Collection being analysed"': 80 , '"Mycobacterium Collection being analysed"': 8560 , '"S. viridans encountered "':450 , '"S. thermophilus Analysis intiated"':300 }
labels = sorted(pDict.keys())
sizes = pDict.values()
k = len(pDict.keys())
# Build Pie chart
list = plt.cm.gist_rainbow(np.linspace(0, 1, k))
ax1 = fig.add_subplot(1,1,1,axisbg = 'grey')
ax1.pie(sizes, labels = labels, colors = list,
autopct='%1.1f%%', startangle=90)
我想把那些值小于10%的项合并成“其他”,然后用pyplot画一个饼图。请问我该怎么把这些小于10%的值合并成“其他”?
输出的饼图应该包含如下结果:
'"Streptococcous targeted"': 678000 , '"s.coccous file read"': 6780 , '"Mycobacterium Collection being analysed"': 8560 , '"others" :800
谢谢!
1 个回答
1
你只需要先对pDict进行筛选,像这样:
psum = sum(pDict.values())
pthreshold = psum * 0.1
includedict = dict(k,v for k,v in pDict.items() if v >= pthreshold)
others = dict(k,v for k,v in pDict.items() if v < pthreshold)
然后其他的部分就和之前一样。
可能有一种方法可以一步完成,不太确定,但这样做是有效的。