Home > Enterprise >  Seaborn - Timeseries line breaks when hue is added
Seaborn - Timeseries line breaks when hue is added

Time:12-11

I am having trouble plotting a timeseries plot using seaborn. By adding hue to the plot the timeseries plot breaks. I can't figure out why the time series plot break in between and how can I stop dates from overlapping.

The code to replicate the issue is below:

test_data = {'Date':['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-06', '2021-01-08', '2021-01-09'],
             'Price':[20, 10, 30, 40, 25, 23, 56],
             'Kind': ['Pre', 'Pre', 'Pre', 'Pre', 'Current', 'Post', 'Post']}
test_df = pd.DataFrame(test_data)
test_df['Date'] = pd.to_datetime(test_df['Date'])
sns.lineplot(data=test_df, x="Date", y="Price", hue='Kind')

How can I fix the line break and dates overlapping?

CodePudding user response:

Try adding the style and markers arguments to handle the isolated point with "Kind" == "Current":

import seaborn as sns
import matplotlib.pyplot as plt

fig = plt.figure()
sns.lineplot(data=test_df, x="Date", y="Price", style='Kind', markers=['o', 'o', 'o'], hue='Kind')
fig.autofmt_xdate()

which displays the plot: enter image description here

  • Related