1

I wish to add a hue to my seaborn lineplot, however the following keeps happening, as shown in the image.

My code is as follows:

plt.figure(figsize=(15,5))
sns.lineplot(x = 'DATETIME', y = 'TOTALDEMAND', data = df_day.loc[df_day['STATE'] == 'NSW'],hue="Season")

Is there a way to have the hue not connect to the next season?

enter image description here

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Rahul
  • 21
  • 1
  • 2
  • You can try changing the linestyle to scatter, see https://stackoverflow.com/questions/51963725/how-to-plot-a-dashed-line-on-seaborn-lineplot – Learning is a mess Apr 08 '22 at 08:42
  • Yeah thats what I was doing, but was curious to see if there was a way to do it in lines – Rahul Apr 08 '22 at 09:14
  • You can use `units` for this although you'll need to contrive a new variable that is a cross between season / yearly cycle. – mwaskom Apr 09 '22 at 03:54

1 Answers1

1

An idea could be to draw the lineplot with a fixed color, and use a scatterplot for colorizing:

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

df = pd.DataFrame({'DATETIME': pd.date_range('20160101', periods=1000, freq='D'),
                   'TOTALDEMAND': np.random.randint(-10, 11, 1000).cumsum() + 30000})
df['SEASON'] = pd.Categorical.from_codes((df.DATETIME.dt.month - 1) // 3, ['winter', 'spring', 'summer', 'autumn'])

plt.figure(figsize=(15, 6))
ax = sns.lineplot(data=df, x='DATETIME', y='TOTALDEMAND', color='black')
sns.scatterplot(data=df, x='DATETIME', y='TOTALDEMAND', s=20, alpha=0.2, hue='SEASON', ax=ax)
sns.despine()
plt.show()

sns.lineplot with hue coloring

JohanC
  • 71,591
  • 8
  • 33
  • 66