gpt4 book ai didi

python - Seaborn:避免绘制缺失值(线图)

转载 作者:太空狗 更新时间:2023-10-30 02:52:46 25 4
gpt4 key购买 nike

我想要一个线图来指示是否缺少一条数据,例如: enter image description here

但是,下面的代码填充了缺失的数据,创建了一个可能具有误导性的图表: enter image description here

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

# load csv
df=pd.read_csv('data.csv')
# plot a graph
g = sns.lineplot(x="Date", y="Data", data=df)
plt.show()

我应该在我的代码中更改什么以避免填充缺失值?

csv 如下所示:

Date,Data
01-12-03,100
01-01-04,
01-02-04,
01-03-04,
01-04-04,
01-05-04,39
01-06-04,
01-07-04,
01-08-04,53
01-09-04,
01-10-04,
01-11-04,
01-12-04,
01-01-05,28
...
01-04-18,14
01-05-18,12
01-06-18,8
01-07-18,8

.csv 链接: https://drive.google.com/file/d/1s-RJfAFYD90m4SrFDzIba7EQP4C-J0yO/view?usp=sharing

最佳答案

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

# Make example data
s = """2018-01-01
2018-01-02,100
2018-01-03,105
2018-01-04
2018-01-05,95
2018-01-06,90
2018-01-07,80
2018-01-08
2018-01-09"""
df = pd.DataFrame([row.split(",") for row in s.split("\n")], columns=["Date", "Data"])
df = df.replace("", np.nan)
df["Date"] = pd.to_datetime(df["Date"])
df["Data"] = df["Data"].astype(float)

三个选项:

1) 使用pandasmatplotlib

2) 如果您需要 seaborn:不是它的用途,而是像您这样的常规日期,您可以开箱即用地使用 pointplot

fig, ax = plt.subplots(figsize=(10, 5))

plot = sns.pointplot(
ax=ax,
data=df, x="Date", y="Data"
)

ax.set_xticklabels([])

plt.show()

enter image description here

3) 如果你需要 seaborn 并且你需要 lineplot:我查看了源代码,它看起来像 lineplot drops nans在绘图之前从 DataFrame 中获取。所以不幸的是,不可能正确地做到这一点。不过,您可以使用一些高级 hackery,并使用 hue 参数将单独的部分放在单独的桶中。我们使用 nans 的出现对部分进行编号。

fig, ax = plt.subplots(figsize=(10, 5))

plot = sns.lineplot(
ax=ax,
data=df, x="Date", y="Data",
hue=df["Data"].isna().cumsum(), palette=["black"]*sum(df["Data"].isna()), legend=False, markers=True
)
ax.set_xticklabels([])

plt.show()

enter image description here

不幸的是,markers 参数目前似乎已损坏,因此如果您想查看两边都有 nans 的日期,则需要修复它。

关于python - Seaborn:避免绘制缺失值(线图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52098537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com