python - 如何避免 matplotlib 饼图中的标签和 autopct 重叠?

标签 python numpy matplotlib plot pie-chart

我的 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()

是否可以显示“一月”、“二月”、“三月”等标签和百分比:

  • 不重叠,或
  • 使用箭头标记

piechart

最佳答案

您也可以将图例放在饼图旁边:

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


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

enter image description here

关于python - 如何避免 matplotlib 饼图中的标签和 autopct 重叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23577505/

相关文章:

python - 在 Python 中使用 Eval 创建类变量

python - 使用 fmin_slsqp 构造最小二乘函数

python - 更改 Matplotlib 图中单词中某些字母的字体类型

python - 逆向工程自动生成的 C?

python xml转字符串,插入postgres

python - 一个阵列轴的快速插补

python - 正确使用 numpy searchsorted 例程

python - 使用 matplotlib 和 markevery 在特定点放置标记时出错

python - 如何获取每行的百分比并可视化分类数据

python - 避免在 Python 中嵌套 for 循环