如何避免Matplotlib绘制的饼图与图例重叠
解决Matplotlib饼图与图例重叠问题
问题说明
使用Matplotlib绘制饼图时,图例与饼图区域出现重叠,影响可视化效果。原代码及重叠效果如下:
原代码
import matplotlib.pyplot as plt import numpy as np y = np.array([1,117,11,5]) mylabels = "Complete","Pass","Fail","Block" mycolors = ["b","g","r","c"] myexplode =[0.6,0,0.4,0] plt.pie(y,labels=mylabels,explode = myexplode,shadow=True,colors = mycolors,autopct ='%1.1f%%') plt.legend(title ="Test result types") plt.show()
重叠效果

解决办法
方法1:指定图例位置与偏移
通过plt.legend()的loc参数设置图例位置,配合bbox_to_anchor调整偏移量,将图例移至饼图外侧:
import matplotlib.pyplot as plt import numpy as np y = np.array([1,117,11,5]) mylabels = "Complete","Pass","Fail","Block" mycolors = ["b","g","r","c"] myexplode =[0.6,0,0.4,0] plt.pie(y,labels=mylabels,explode = myexplode,shadow=True,colors = mycolors,autopct ='%1.1f%%') # 将图例放在饼图右侧,通过bbox_to_anchor调整位置避免重叠 plt.legend(title ="Test result types", loc="upper right", bbox_to_anchor=(1.3, 1)) plt.show()
方法2:自动调整布局
使用plt.tight_layout()让Matplotlib自动调整元素间距,也可提前设置画布尺寸预留空间:
import matplotlib.pyplot as plt import numpy as np # 设置合适的画布尺寸 fig, ax = plt.subplots(figsize=(8, 6)) y = np.array([1,117,11,5]) mylabels = "Complete","Pass","Fail","Block" mycolors = ["b","g","r","c"] myexplode =[0.6,0,0.4,0] ax.pie(y,labels=mylabels,explode = myexplode,shadow=True,colors = mycolors,autopct ='%1.1f%%') ax.legend(title ="Test result types") # 自动调整布局,避免元素重叠 plt.tight_layout() plt.show()
方法3:仅保留图例展示标签
若饼图自带标签与图例重复,可去掉饼图的labels参数,仅通过图例展示分类:
import matplotlib.pyplot as plt import numpy as np y = np.array([1,117,11,5]) mylabels = ["Complete","Pass","Fail","Block"] mycolors = ["b","g","r","c"] myexplode =[0.6,0,0.4,0] # 不显示饼图自带标签 plt.pie(y,explode = myexplode,shadow=True,colors = mycolors,autopct ='%1.1f%%') # 图例传入自定义标签并调整位置 plt.legend(title ="Test result types", labels=mylabels, loc="upper right", bbox_to_anchor=(1.3, 1)) plt.show()
内容的提问来源于stack exchange,提问作者PChao
相关产品推荐
相关产品推荐

