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

含NaN值的Bubble plot(气泡图)绘制实现问题咨询

问题原因

你代码失效的核心原因是 NaN无法通过==运算符判断:np.nan和任何值做相等判断的返回结果都是False,包括和它自身比较,所以你写的height==np.nan筛选不到任何符合条件的行。

正确实现代码
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 示例DataFrame,你可以替换为自己的数据集
df = pd.DataFrame({
    'x': [1,2,3,4,5,6],
    'y': [1,5,10,7,6,12],
    'height': [np.nan, 20, 100, np.nan, np.nan, 500]
})

# 按height是否为空拆分两组数据
non_null_data = df[df['height'].notna()]
null_data = df[df['height'].isna()]

# 绘图
fig = plt.figure()
ax = fig.add_subplot()
# 非空值绘制黑色圆形气泡,s参数可以乘系数调整气泡大小
ax.scatter(non_null_data['x'], non_null_data['y'], marker='o', c='k', s=non_null_data['height'])
# 空值绘制红色三角标记
ax.scatter(null_data['x'], null_data['y'], marker='^', c='r')

plt.show()
补充说明
  • 判断空值统一用pandas内置的isna()/notna()方法,或者numpy的np.isnan(),不要用== np.nan的写法
  • 如果觉得气泡尺寸不符合预期,可以给s参数的height值乘缩放系数调整,比如s=non_null_data['height'] * 2
  • 需要图例的话可以在scatter方法里加label参数,最后调用plt.legend()展示即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:45:02