4

I have problem with sns lineplot and scatterplot. Basically what I'm trying to do is to connect dots of a scatterplot to present closest line joining mapped points. Somehow lineplot is changing width when facing points with tha same x axis values. I want to lineplot to be same, solid line all the way.

The code:

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

data = {'X': [13, 13, 13, 12, 11], 'Y':[14, 11, 13, 15, 20], 'NumberOfPlanets':[2, 5, 2, 1, 2]}
cts = pd.DataFrame(data=data)

plt.figure(figsize=(10,10))
sns.scatterplot(data=cts, x='X', y='Y', size='NumberOfPlanets', sizes=(50,500), legend=False)
sns.lineplot(data=cts, x='X', y='Y',estimator='max', color='red')
plt.show()

The outcome:

enter image description here

Any ideas?

EDIT:

If I try using pyplot it doesn't work either: Code:

plt.plot(cts['X'], cts['Y'])

Outcome:

enter image description here

I need one line, which connects closest points (basically what is presented on image one but with same solid line).

dtBane
  • 91
  • 1
  • 6
  • Probably you want `sns.lineplot(..., estimator='max', ci=None)` to suppress the confidence interval shown by default. – JohanC Jan 29 '22 at 23:36
  • 2
    I edited post with reproducible data. – dtBane Jan 29 '22 at 23:37
  • `ci=None` did not help. The faded line disappeared entirely. – dtBane Jan 30 '22 at 09:47
  • Yes, it should disappear as you only show the `'max'`. `sns.lineplot` only uses one `y` value per `x`. If you just want to connect your points, you can directly use matplotlib's line plot on top of the seaborn scatterplot. E.g. `plt.plot(cts['X'], cts['Y'], color='red', lw=2)`. – JohanC Jan 30 '22 at 11:16
  • If I use `plt.plot(cts['X'], cts['Y'])` it's still not my desired outcome, since it connects to the middle dot and then to one above and below. I need one line connecting closest points. Picture in edited post. – dtBane Jan 30 '22 at 12:18

1 Answers1

1

Ok, I have finally figured it out. The reason lineplot was so messy is because data was not properly sorted. When I sorted dataframe data by 'Y' values, the outcome was satisfactory.

data = {'X': [13, 13, 13, 12, 11], 'Y':[14, 11, 13, 15, 20], 'NumberOfPlanets':[2, 5, 2, 1, 2]}
cts = pd.DataFrame(data=data)
cts = cts.sort_values('Y')

plt.figure(figsize=(10,10))
plt.scatter(cts['X'], cts['Y'], zorder=1)
plt.plot(cts['X'], cts['Y'], zorder=2)
plt.show()

Now it works. Tested it also on other similar scatter points. Everything is fine :) Thanks!

dtBane
  • 91
  • 1
  • 6