Matplotlib:绘制轴外的两个图例使其被图框切断

时间:2016-06-01 09:29:39

标签: python-2.7 matplotlib plot legend

任务:

在圆轴外绘制带有两个图例的圆环图(第一个图例 - 相对于图的右侧,第二个 - 位于底部)。

问题:

保存图形时,第1个图例的一部分被切掉[特别是当它包含长文本时,请参见下面的示例] [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 :(得分:0)

此问题附带饼图:https://github.com/matplotlib/matplotlib/issues/4251

并没有修复。