如何避免matplotlib饼图中的标签和autoct重叠?

2024-05-15 18:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

  • 没有重叠,或者
  • 使用arrow mark

piechart


Tags: 代码labelspltaprjunmarsepmay
2条回答

试试紧身衣。

plt.tight_layout()

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

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

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

相关问题 更多 >