python - 高压图 : Plotting multiple lines with null values

标签 python pandas google-colaboratory hvplot

我有一个 DataFrame,我正在尝试使用 HV 图绘制图表。

到目前为止,我有这样的事情:

new_df = new_df.dropna(subset=['Reflectance'])
new_df = new_df.sort_values(by='Wavelength')

reflectance_plot = new_df.hvplot.line(x = "Wavelength",y = "Reflectance", by="UniqueID", legend=False).opts(fontsize={'title': 16, 'labels': 14, 'yticks': 12},xrotation=45, xticks=15)
reflectance_plot

这给了我这样的东西: enter image description here

正如您所看到的,在有数据的平滑区域之间,有很多没有值的直线。我试图删除这些直线,以便仅绘制数据。我尝试用这段代码来做到这一点:

new_df['Reflectance'] = new_df['Reflectance'].fillna(np.nan).replace([np.nan], [None])
new_df = new_df.sort_values(by='Wavelength')
    
reflectance_plot = new_df.hvplot.line(x = "Wavelength",y = "Reflectance", by="UniqueID", legend=False).opts(fontsize={'title': 16, 'labels': 14, 'yticks': 12},xrotation=45, xticks=15)
reflectance_plot

这给我留下了: enter image description here

很明显,这就是我想要实现的目标,只不过现在绝大多数数据已经完全消失了。对于为什么会发生这种情况以及如何解决它,我将不胜感激任何建议或见解。

最佳答案

我遇到了类似的问题,我的想法如下:

生成并绘制一些有问题的数据:

import pandas as pd
import numpy as np
import hvplot.pandas

df = pd.DataFrame({'data1':np.random.randn(22),
                   'data2':np.random.randn(22)+3})

df['time'] = pd.to_datetime('2022-12-25T09:00') + \
             np.cumsum(([pd.Timedelta(1, unit='h')]*5 +
                       [pd.Timedelta(30, unit='h')] + # <-- big 'Ol gap in the data
                       [pd.Timedelta(1, unit='h')]*5)*2)

df.set_index('time', inplace=True)
df.hvplot()

绘制如下图所示的内容 - 数据中的差距希望是明显的(但并不总是如此): plot with gaps

因此,方法是找到数据中长得令人无法接受的间隙。这将根据具体情况而定。在上面的数据中,好的数据相隔 1 小时,间隙为 30 小时 - 所以我使用最大可接受的间隙 2 小时:

# Insert NA just after any gaps which are unacceptably long:
dt_max_acceptable = pd.Timedelta(2, unit='h')

df['dt'] = df.index.to_series().diff()
t_at_end_of_gaps = df[df.dt > dt_max_acceptable].index.values
t_before_end_of_gaps = [i - pd.Timedelta(1) for i in t_at_end_of_gaps]

for t in t_before_end_of_gaps:
    df.loc[t] = pd.NA
    
df.sort_index(inplace=True)
df.hvplot()

应该绘制类似这样的内容 - 显示该线不再跨越“太长”的间隙:

plot where line no longer spans the gaps

该方法非常容易应用 - 并且适合我的目的。缺点是它会添加含有 NaN 数据的人工行 - 这可能并不总是可以接受的。

关于python - 高压图 : Plotting multiple lines with null values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73169411/

相关文章:

python - 使用 pandas DataFrame 写入数据时出现无属性 "append"错误

python - 上传 Csv 文件 Google colab

user-interface - Colab 上的简单 UI

pandas - 修改 pandas barplot 中的错误栏范围

python - 如何在 Python 的同一行上打印变量和字符串?

python - Python 标题的正确大写

python - 使用 Pandas 操作多列

python - 从 Pandas 数据框中删除行和列

google-colaboratory - 如何在 Google 合作实验室安装支持 GPU 的 LightGBM

python - Pandas groupby 自定义组