matplotlib 运行后出现冗余结果请教解答

matplotlib 运行后出现冗余结果

# explode = (0, 0.1, 0.1, 0)
fig=plt.figure(figsize=[12,5],facecolor='c',dpi=150)
y1=list(shouru_分业务_1.loc['total',:])
y2=list(shouru_分业务_2021_1.loc['total',:])
ax1=fig.add_subplot(121)
ax2=fig.add_subplot(122)
# ax2=ax1.twinx()
lable1=shouru_分业务_1.columns
lable2=shouru_分业务_2021_1.columns

ax1.pie(y1,labels=lable1,shadow=True,autopct='%1.1f%%',startangle=90,pctdistance=0.6)
ax2.pie(y2,labels=lable2,shadow=True,autopct='%1.1f%%',startangle=90,pctdistance=0.6)

img

这段代码是在使用 matplotlib 库绘制饼图。

在调用 fig.add_subplot(121) 和 fig.add_subplot(122) 创建子图后,在 ax1 和 ax2 上绘制饼图。

可能是因为在绘制第二个饼图时,没有正确指定 ax2 这个子图。

修改代码如下:

fig=plt.figure(figsize=[12,5],facecolor='c',dpi=150)
y1=list(shouru_分业务_1.loc['total',:])
y2=list(shouru_分业务_2021_1.loc['total',:])
ax1=fig.add_subplot(121)
ax2=fig.add_subplot(122)
lable1=shouru_分业务_1.columns
lable2=shouru_分业务_2021_1.columns
ax1.pie(y1,labels=lable1,shadow=True,autopct='%1.1f%%',startangle=90,pctdistance=0.6)
ax2.pie(y2,labels=lable2,shadow=True,autopct='%1.1f%%',startangle=90,pctdistance=0.6)

另外,你还可以考虑给每个子图指定标题,便于识别。

ax1.set_title('shouru_分业务_1')
ax2.set_title('shouru_分业务_2021_1')

出现冗余结果的原因可能是因为你没有设置ax1和ax2的标题或标签,或者在调用add_subplot()函数时使用了相同的参数。如果你希望在同一个图片中显示两个饼图,可以在调用add_subplot()函数时使用不同的参数来创建两个不同的子图。例如:

ax1=fig.add_subplot(121)
ax2=fig.add_subplot(122)

另外,你可以使用ax1.set_title()和ax2.set_title()来设置子图的标题,用ax1.legend()和ax2.legend()来设置图例。

如果你希望同时在一个图片中显示两个饼图,你可以使用subplots()函数来创建一个子图网格。

fig, axs = plt.subplots(1, 2, figsize=[12, 5], dpi=150)
ax1, ax2 = axs[0], axs[1]
ax1.pie(y1, labels=lable1, shadow=True, autopct='%1.1f%%', startangle=90, pctdistance=0.6)
ax2.pie(y2, labels=lable2, shadow=True, autopct='%1.1f%%', startangle=90, pctdistance=0.6)

这样你就可以在同一个图片中显示两个饼图了。