Skip to main content
 首页 » 编程设计

Python之情节旁边的图例和保存的图中

2025年02月15日7Terrylee

我一直在整个论坛中搜索,但我还没有找到我的问题的答案。

我想创建两个彼此相邻的饼图,旁边有一个图例。

labels = ['0-20', '20-40',  '40-60', '60-80', '80-100', '100-120'] 
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'orange', 'grey'] 
 
fig, [ax1, ax2] = plt.subplots(1,2) 
ax1.pie(groen, colors = colors, startangle = 90, counterclock = False) 
ax1.axis('equal') 
 
ax2.pie(rood, colors = colors, startangle = 90, counterclock = False) 
ax2.axis('equal') 
plt.legend(labels, loc = 'best')#, bbox_to_anchor=(0.5, 0), mode = 'expand', ncol = 2) 

我一直在尝试一些东西,但不幸的是没有结果。出问题的是图例没有完全出现在保存的图像中,如下所示。我也有一个白色条,图例的顺序错误。我想从左到右,从上到下阅读。

欢迎任何帮助;)

请您参考如下方法:

当使用下面的代码时

import matplotlib.pyplot as plt 
groen = rood = [7,8,12,4,9,5] 
labels = ['0-20', '20-40',  '40-60', '60-80', '80-100', '100-120'] 
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'orange', 'grey'] 
 
fig, [ax1, ax2] = plt.subplots(1,2) 
ax1.pie(groen, colors = colors, startangle = 90, counterclock = False) 
ax1.axis('equal') 
 
ax2.pie(rood, colors = colors, startangle = 90, counterclock = False) 
ax2.axis('equal') 
plt.legend(labels, loc = 8, ncol = 2) 
 
plt.savefig(__file__+".png", bbox_inches="tight") 
plt.show() 

我猜一切都按预期工作。请注意 bbox_inches="tight" 参数,它会缩小或扩大图形大小,从而不会裁剪任何内容。