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

如何在Plotly Python饼图中为全零值添加占位文本

解决Plotly饼图值全为0时显示占位内容的方法

你可以通过判断values_allDevicesPassed中的值是否全为0,来决定是添加饼图还是显示占位文本,具体实现如下:

修改后的代码

# 判断所有值是否为0
all_zero = all(v == 0 for v in values_allDevicesPassed)

if not all_zero:
    # 正常添加饼图
    fig.append_trace(go.Pie(labels=labels_allDevicesPassed,
               values=values_allDevicesPassed,
               showlegend=False,
               textposition='inside',
               hovertemplate=hover_value3,
               domain=dict(x=[0, 1]),
               textinfo='value'), row=2, col=2)
else:
    # 添加占位文本注释
    fig.add_annotation(
        text="无设备可展示",
        xref="x domain",
        yref="y domain",
        x=0.5,  # 水平居中
        y=0.5,  # 垂直居中
        showarrow=False,
        font=dict(
            family="monospace",
            size=25,
            color="black"
        ),
        row=2, col=2
    )

fig.update_layout(
    font=dict(
        family="monospace",
        size=25,
        color="black"
    )
)
fig.show()

关键说明

  • 用all(v == 0 for v in values_allDevicesPassed)快速判断所有值是否为0
  • 当值全为0时,使用add_annotation在指定的row=2, col=2位置添加居中的占位文本,替代无法显示的饼图
  • 注释的字体样式可以和全局布局保持一致,保证视觉统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 17:04:50