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

使用Seaborn绘制时间轴折线图时NaN值未显示缺口如何解决

Seaborn折线图空值位置显示缺口解决方法

问题原因

Seaborn的lineplot默认有两个特性导致空值位置不会显示缺口:

  • 自动跳过Values列的NaN值,直接连接前后相邻的非空数据点
  • 默认对相同x轴(Time列)的数值做聚合计算,会掩盖同时间点的空值情况

解决方法

方法1:使用Matplotlib原生绘图(最简单推荐)

Matplotlib的plot方法原生支持遇到NaN值自动断开折线,只需要调整绘图逻辑即可,同时可以保留Seaborn的样式设置:

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

df = pd.read_csv("Data.csv")
# 先将时间列转为datetime格式,保证时间顺序正确
df['Time'] = pd.to_datetime(df['Time'])

sns.set(rc={'figure.figsize':(13,4)})
# 用matplotlib原生plot替代seaborn lineplot
fig, ax = plt.subplots()
ax.plot(df['Time'], df['Values'])
ax.set(xlabel='Time', ylabel='Values')
plt.xticks(rotation=90)
plt.tight_layout()
plt.show()

方法2:保留Seaborn lineplot的实现方案

如果需要使用Seaborn lineplot的其他特性,可以先对连续非空值分组,每组单独绘制折线:

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

df = pd.read_csv("Data.csv")
df['Time'] = pd.to_datetime(df['Time'])
# 按照NaN位置分组,连续非空值属于同一组
df['group'] = df['Values'].isna().cumsum()

sns.set(rc={'figure.figsize':(13,4)})
ax = sns.lineplot(x="Time", y="Values", hue="group", data=df, estimator=None, legend=False)
ax.set(xlabel='Time', ylabel='Values')
plt.xticks(rotation=90)
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:24:02