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

Сте*_*нов 5 python visualization seaborn

我想要一个线图来指示是否缺少一条数据,例如: 在此处输入图片说明

但是,下面的代码填充了丢失的数据,从而创建了可能引起误解的图表: 在此处输入图片说明

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()
Run Code Online (Sandbox Code Playgroud)

我应该在代码中进行哪些更改以避免填充缺失值?

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
Run Code Online (Sandbox Code Playgroud)

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

Dzm*_*rka 7

尝试将 NaN 值设置为np.inf-- Seaborn 不会绘制这些点,并且不会将之前的点与之后的点连接起来。

  • 不正确,请自行尝试以下代码(通过添加/删除 inf 部分): ``` x = np.arange(10.); y = (-1) ** x; y[5] = np.nan;y[5] = np.inf; df = pd.DataFrame({'x': x, 'y': y}); sns.lineplot(数据=df, x='x', y='y'); ```` (2认同)

Den*_*loe 5

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)
Run Code Online (Sandbox Code Playgroud)

三种选择:

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

3)如果需要seaborn,则需要lineplot:我已经看过源代码,并且看起来像lineplot在绘制之前从DataFrame中删除了nans。因此,很遗憾,无法正确执行此操作。但是,您可以使用一些高级黑客工具,并使用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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

不幸的是,markers参数当前似乎已断开,因此,如果您想查看两边都有nans的日期,则需要对其进行修复。


Tre*_*ney 1

  • 由于数据已经在 a 中pandas.DataFrame,最简单的解决方案是直接使用 进行绘图pandas.DataFrame.plot,它用作matplotlib默认绘图后端。
    • 顺便说一句,seaborn是一个高级 API matplotlib
  • 测试于python 3.11.2, pandas 2.0.0,matplotlib 3.7.1
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# load the csv file
df = pd.read_csv('d:/data/hh.ru_stack.csv')

# convert the date column to a datetime.date
df.Date = pd.to_datetime(df.Date, format='%d-%m-%y').dt.date

# plot with markers
ax = df.plot(x='Date', marker='.', figsize=(9, 6))

# set the ticks for every year if desired
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

fig, ax = plt.subplots(figsize=(9, 6))
ax.plot('Date', 'Stagnation', '.-', data=df)
ax.legend()

ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述