You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib中pie()无法调整饼图尺寸的问题求助

调整Matplotlib饼图尺寸(保持Figure大小不变)

你的原始代码:

import pandas as pd 
import numpy as np 
df = pd.read_csv("Medals.csv")
import matplotlib.pyplot as plt
fig=plt.figure()
plt.suptitle("Medals data")
x = sum(df.Gold)
y = sum(df.Silver)
z = sum(df.Bronze)
y = np.array([x,y,z])
mylabels = ["Gold", "Silver", "Bronze"]
plt.pie(y,labels = mylabels,startangle=0,autopct='%1.1f%%')
plt.axis('equal')
plt.legend(["Gold","Silver","Bronze"],loc ="lower right")
fig.savefig("plot7.png")

下面提供两种可行的解决方法:

方法1:用radius参数缩小饼图+调整图例位置

你之前用radius没生效,大概率是图例和饼图重叠导致视觉上没变化,修改后代码如下:

import pandas as pd 
import numpy as np 
df = pd.read_csv("Medals.csv")
import matplotlib.pyplot as plt
fig=plt.figure()
plt.suptitle("Medals data")
x = sum(df.Gold)
y = sum(df.Silver)
z = sum(df.Bronze)
y = np.array([x,y,z])
mylabels = ["Gold", "Silver", "Bronze"]
# 设置radius参数缩小饼图,数值越小饼图越小
plt.pie(y,labels = mylabels,startangle=0,autopct='%1.1f%%', radius=0.7)
plt.axis('equal')
# 将图例移到饼图外侧,避免重叠
plt.legend(mylabels, loc="upper right", bbox_to_anchor=(1.3, 0.9))
# 保存时加上bbox_inches='tight',防止图例被截断
fig.savefig("plot7.png", bbox_inches='tight')

方法2:自定义Axes区域控制饼图大小

通过创建指定尺寸的Axes,精准控制饼图在Figure中的占比,完全不改变Figure本身的尺寸:

import pandas as pd 
import numpy as np 
df = pd.read_csv("Medals.csv")
import matplotlib.pyplot as plt
fig=plt.figure()
plt.suptitle("Medals data")
# 创建自定义Axes,参数为[left, bottom, width, height],取值范围0-1
# 例如[0.2,0.2,0.6,0.6]表示Axes从Figure的20%位置开始,宽度和高度各占60%
ax = fig.add_axes([0.2, 0.2, 0.6, 0.6])
x = sum(df.Gold)
y = sum(df.Silver)
z = sum(df.Bronze)
y = np.array([x,y,z])
mylabels = ["Gold", "Silver", "Bronze"]
ax.pie(y,labels = mylabels,startangle=0,autopct='%1.1f%%')
ax.axis('equal')
ax.legend(mylabels, loc="lower right")
fig.savefig("plot7.png")

内容的提问来源于stack exchange,提问作者Vineet Pashine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 22:23:28