Matplotlib:在轴外绘制两个图例会被图形框截断

3

任务:

绘制一个带有两个图例的甜甜圈图,其中第一个图例在轴的右侧(相对于图形),第二个图例在底部。

问题:

保存图像时,第一个图例的一部分被裁剪掉了[特别是当它包含长文本时,如下所示的例子] [1]

期望结果:

通过考虑两个图例的尺寸来紧凑地布局图形。


代码:

import matplotlib.pyplot as plt
from pylab import *

ioff() # don't show figures 

colors = [(102, 194, 165), (252, 141, 98), (141, 160, 203), (231, 138,195),  
          (166, 216, 84), (255, 217, 47), (171, 197, 233), (252, 205, 229)]

for icol in range(len(colors)):
    red,green,blue = colors[icol]
    colors[icol] = (red / 255., green / 255., blue / 255.)

fig = plt.figure(1, figsize=(8, 8))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

sizes_component_1 = [12, 23, 100, 46]
sizes_component_2 = [15, 30, 45, 10, 44, 45, 50, 70]

component_1 = 'exampleofalongtextthatiscutoff', '2', '3', '4'
component_2 = 'Unix', 'Mac', 'Windows7', 'Windows10', 'WindowsXP', 'Linux', 'FreeBSD', 'Android'

patches1, texts1, autotexts1 = ax.pie(sizes_component_1, radius=1, pctdistance=0.9, colors=colors, autopct='%1.1f%%', shadow=False, startangle=90)
patches2, texts2, autotexts2 = ax.pie(sizes_component_2, radius=0.8, pctdistance=0.6, colors=colors, autopct='%1.1f%%', shadow=False, startangle=90)

# To draw circular donuts
ax.axis('equal')

# Draw white circle
centre_circle = plt.Circle((0,0),0.6,color='black', fc='white')         
ax.add_artist(centre_circle)

# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])

lgd1=ax.legend(patches1,component_1, frameon=False, loc='center left', bbox_to_anchor=(1.0, 0.8), borderaxespad=0.1)
lgd2=ax.legend(patches2,component_2, frameon=False, loc='center left', ncol=len(patches2)/2, bbox_to_anchor=(0.0, -0.005), borderaxespad=0)

ax_elem = ax.add_artist(lgd1)

fig.suptitle('Title', fontsize=16)
fig.savefig('donut.png',bbox_extra_artists=(lgd1,lgd2,), bbox_inches='tight')
plt.gcf().clear() # clears buffer
1个回答

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接