'Piecewise python/seaborn plot with segmented lines?

I'm trying to use seaborn to make lineplots of a few variables, but I'm trying to make sure that lines are segmented when not continuous. Example below:

df = pd.DataFrame([[1, np.nan], [2, np.nan], [np.nan, np.nan],
                   [np.nan, 1], [np.nan, 2], [4, np.nan], [6, np.nan]],
                   columns=['cat', 'dog'])
display(df)
plt.plot(df['cat'])
plt.plot(df['dog'])

enter image description here enter image description here

When I try to do the plotting in seaborn I get:

sns.lineplot(data=df)

enter image description here

Or using the dataframe format that I prefer:

df = pd.DataFrame([[1, 'cat'],[2, 'cat'], [np.nan, np.nan],
                   [1, 'dog'], [2, 'dog'], [4, 'cat'], [6, 'cat']],
                   columns=['value', 'type'])
display(df)
sns.lineplot(data=df, x=df.index, y='value', hue='type')

enter image description here enter image description here

SO... Is there a way to do a seaborn plot that looks piecewise like the first plot that was created using matplotlib/pyplot? Can it be done using the 2nd dataframe format with a value column and a category column?



Solution 1:[1]

  1. drop rows where every value is NAN
  2. replace remaining NaN with np.inf
  3. plot with seaborn.lineplot

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Riley