Python 如何避免在 matplotlib 饼图中标签和 autopct 重叠?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23577505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:10:58  来源:igfitidea点击:

How to avoid overlapping of labels & autopct in a matplotlib pie chart?

pythonnumpymatplotlibplotpie-chart

提问by user123

My Python code is:

我的 Python 代码是:

values = [234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7]
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul','Aug','Sep','Oct', 'Nov','Dec']

colors = ['yellowgreen', 'red', 'gold', 'lightskyblue', 
          'white','lightcoral','blue','pink', 'darkgreen', 
          'yellow','grey','violet','magenta','cyan']

plt.pie(values, labels=labels, autopct='%1.1f%%', shadow=True, 
        colors=colors, startangle=90, radius=1.2)

plt.show()

Is it possible to show the labels "Jan", "Feb", "Mar", etc. and the percentages, either:

是否可以显示标签“Jan”、“Feb”、“Mar”等以及百分比:

  • without overlapping, or
  • using an arrow mark?
  • 不重叠,或
  • 使用arrow mark?

piechart

饼形图

采纳答案by Saullo G. P. Castro

Alternatively you can put the legends beside the pie graph:

或者,您可以将图例放在饼图旁边:

import matplotlib.pyplot as plt
import numpy as np

x = np.char.array(['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct', 'Nov','Dec'])
y = np.array([234, 64, 54,10, 0, 1, 0, 9, 2, 1, 7, 7])
colors = ['yellowgreen','red','gold','lightskyblue','white','lightcoral','blue','pink', 'darkgreen','yellow','grey','violet','magenta','cyan']
porcent = 100.*y/y.sum()

patches, texts = plt.pie(y, colors=colors, startangle=90, radius=1.2)
labels = ['{0} - {1:1.2f} %'.format(i,j) for i,j in zip(x, porcent)]

sort_legend = True
if sort_legend:
    patches, labels, dummy =  zip(*sorted(zip(patches, labels, y),
                                          key=lambda x: x[2],
                                          reverse=True))

plt.legend(patches, labels, loc='left center', bbox_to_anchor=(-0.1, 1.),
           fontsize=8)

plt.savefig('piechart.png', bbox_inches='tight')

enter image description here

在此处输入图片说明



EDIT: if you want to keep the legend in the original order, as you mentioned in the comments, you can set sort_legend=Falsein the code above, giving:

编辑:如果您想按照原始顺序保留图例,正如您在评论中提到的,您可以sort_legend=False在上面的代码中进行设置,给出:

enter image description here

在此处输入图片说明

回答by real_aravind

Try tightlayout.

尝试紧布局。

plt.tight_layout()

at the end of your code. It may prevent the overlap a little bit.

在您的代码末尾。它可以稍微防止重叠。