本文提供一种鲁棒、可扩展的 python 函数,用于自动判断任意 plotly 图表(包括 `graph_objects` 和 `express` 生成的图表)是否为空,无需渲染或人工检查,适用于 api 返回图表对象的自动化校验场景。
在构建数据可视化流水线时,常需对接外部 API 获取 Plotly 图表对象(如 plotly.graph_objects.Figure 或 plotly.express 返回的 Figure),但无法预知其输入数据是否为空。若直接渲染空图,不仅浪费资源,还可能引发前端异常或误导用户。因此,亟需一个不依赖渲染、不访问原始 DataFrame、兼容所有 Plotly 图形类型的空图检测机制。
上述需求的核心在于:Plotly 图表的“空”本质是其 figure.data 中所有 trace(轨迹)均未携带有效可视化数据。不同 trace 类型(如 Scatter, Bar, Choropleth, Sunburst)判定“空”的依据各不相同——有的依赖 x/y 数组长度,有的依赖 z(热力图)、lat/lon(地图类)、values(树图类)等特有字段。原方案通过硬编码键名列表(['x', 'y', 'z', ...])并逐项检查长度,虽对简单图表有效,但存在明显缺陷:
以下是一个经多类型验证的健壮检测函数,覆盖 plotly.graph_objects 与 plotly.express 所有主流图表:
import plotly.graph_objects as go
import plotly.express as px
def check_empty_plot(figure):
"""
判断 Plotly Figure 是否为空图表。
支持类型:Scatter, Bar, Line, Area, Violin, Choropleth, Sunburst,
Treemap, Pie, Timeline, Scattermapbox, LineMapbox 等。
Args:
figure (plotly.graph_objects.Figure or plotly.express.Figure):
待检测的 Plotly 图表对象
Returns:
bool: True 表示图表为空(无有效数据),False 表示非空。
"""
def is_trace_empty(trace):
# 1. 检查 trace 是否为 None 或空字典
if not trace or not isinstance(trace, dict):
return True
# 2. 处理常见空值标识
if "x" in trace and trace["x"] is None:
return True
if "y" in trace and trace["y"] is None:
return True
if "z" in trace:
z_val = trace["z"]
if z_val is None or (hasattr(z_val, '__len__') and len(z_val) == 0):
return True
if "values" in trace and (trace["values"] is None or
(hasattr(trace["values"], '__len__') and len(trace["values"]) == 0)):
return True
if "lat" in trace and (not trace["lat"] or
(hasattr(trace["lat"], '__len__') and len(trace["lat"]) == 0)):
return True
if "lon" in trace and (not trace["lon"] or
(hasattr(trace["lon"], '__len__') and len(trace["lon"]) == 0)):
return True
if "text" in trace:
text_val = trace["text"]
if text_val is None:
return True
if isinstance(text_val, str) and not text_val.strip():
return True
if hasattr(text_val, '__len__') and len(text_val) == 0:
return True
# 3. 检查核心数值数组(x/y/z/values/lat/lon)是否至少有一个非空
for key in ["x", "y", "z", "values", "lat", "lon"]:
if key in trace:
val = trace[key]
if val is not None and hasattr(val, '__len__') and len(val) > 0:
return False
if isinstance(val, (list, tuple, set)) and val: # 显式非空容器
return False
# 4. 特殊处理 marker/colorscale 等嵌套结构(仅当其他主字段为空时)
if "marker" in trace and isinstance(trace["marker"], dict):
marker = trace["marker"]
if "size" in marker and hasattr(marker["size"], '__len__') and len(marker["size"]) > 0:
return False
if "color" in marker and hasattr(marker["color"], '__len__') and len(marker["color"]) > 0:
return False
return True # 所有检查均未发现有效数据
# 主逻辑:figure.data 为空元组 → 绝对为空
if not hasattr(figure, 'data') or figure.data == tuple():
return True
# 所有 trace 均为空 → 整体为空
return all(is_trace_empty(trace) for trace in figure.data)✅ 该函数优势:
⚠️ 使用注意事项:
匹配),仅检测“是否含数据”; 通过此函数,您可将图表空值校验无缝集成至 CI/CD 流程或 API 响应中间件,真正实现“零人工、全自动、全兼容”的可视化质量保障。