Connecting a closed loop in seaborn.lineplot?

Viewed 110

I have a list of 2d points I can plot in seaborn with a lineplot, but I want to connect the last point back to the first. It seems that simply adding the first point to the end of the DataFrame should be sufficient, but for some reason this does not work. My current solution is to just add another line segment with a whole new call to lineplot, but that seems like overkill. Can I do better?

(Using a built-in dataset for illustration):

import seaborn as sns
import pandas as pd
sns.set_theme()

# Load an example dataset
tips = sns.load_dataset("tips")

mydata = tips[:10]  # Just to make it short

# Copy the first row to the end and plot it all:
mydata = pd.concat([mydata, mydata[:1]], ignore_index = True)
sns.lineplot(data=mydata, x="total_bill", y="tip", sort=False)

open_path_missing_segment

The current solution is to add this line (or, you know, not use seaborn):

sns.lineplot(data=mydata.iloc[[0,-1]], x="total_bill", y="tip", sort=False)

enter image description here

(Color just for emphasis)

How can we make a single lineplot() call build the entire closed loop?

1 Answers

@JohanC gave the comment that led to discovering the answer...

Seaborn seems to group together rows with the same x-value.

Looking at the seaborn.lineplot docs, the way to change this is with the estimator parameter (which, by defaults, aggregates to the mean y value for a given x):

sns.lineplot(data=mydata, x="total_bill", y="tip", sort=False, estimator=None)

enter image description here

Related