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

如何解决饼图中灰色与黑色数值(0.4%)重叠问题并手动定位数值?

解决环形饼图小百分比标签重叠问题及手动定位方法

问题原因

两个极小类别("Gezici"和"Prefabrik")占比均为0.4%,默认的百分比标签位置重叠,导致无法清晰查看。以下是几种可行的解决方法:


方法1:手动调整重叠标签位置

直接获取饼图生成的百分比文本对象,修改其坐标实现分离。

修改后的完整代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

df=pd.DataFrame({'Fiziki Durum':[173,76,1,1]},index=['Bina İçerisinde','Müstakil','Gezici','Prefabrik'])

labels='Bina İçerisinde','Müstakil','Gezici','Prefabrik'
colors=('#3a88e2','#5c9e1e','#708090','#0e1111')

fig1, ax=plt.subplots()

sizes=[173,76,1,1]
explode = (0.05,0.05,0.05,0.05)

# 生成饼图,获取文本对象
patches, texts, autotexts = ax.pie(sizes, colors=colors, startangle=90,explode=explode, autopct='%1.1f%%')

# 手动调整两个小标签的坐标,避免重叠
autotexts[2].set_position((1.2, -0.2))  # 调整"Gezici"标签位置
autotexts[3].set_position((1.2, -0.3))  # 调整"Prefabrik"标签位置

plt.legend(patches, labels, loc='upper center', bbox_to_anchor=(0.5, 0.08), ncol=4, frameon=False)

# 绘制中心白色圆形,制作环形饼图
centre_circle = plt.Circle((0,0),0.70,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

ax.axis('equal')  
plt.tight_layout()
plt.show()

说明:

  • autotexts是饼图百分比标签的列表,索引对应sizes的顺序
  • set_position((x,y))中的坐标可根据实际显示效果微调:x值越大标签越靠右,y值越小标签越靠下

方法2:完全手动添加标签(更灵活)

放弃autopct参数,手动计算百分比并通过annotate函数定位每个标签,精准控制位置。

示例代码片段:

# 计算每个类别的百分比
total = sum(sizes)
percentages = [f'{(s/total)*100:.1f}%' for s in sizes]

# 手动添加标签,中心类别的标签放在饼块中心,小类别放在外侧
ax.annotate(percentages[0], xy=patches[0].center, ha='center', va='center')
ax.annotate(percentages[1], xy=patches[1].center, ha='center', va='center')
ax.annotate(percentages[2], xy=(1.3, -0.15), ha='left', va='center')
ax.annotate(percentages[3], xy=(1.3, -0.3), ha='left', va='center')

说明:

  • xy参数控制标签的绝对坐标
  • ha(水平对齐)和va(垂直对齐)可优化标签的显示效果

方法3:合并极小类别(业务允许时)

如果不需要单独展示这两个小类别,可将它们合并为“其他”类别,从根源避免重叠问题。

修改后的核心代码:

sizes=[173,76,2]  # 合并两个1为2
labels='Bina İçerisinde','Müstakil','Diğer'  # 新增"Diğer"(其他)标签
colors=('#3a88e2','#5c9e1e','#808080')  # 对应新增标签的颜色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:50:26