使用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
相关产品推荐
相关产品推荐

