Search code examples
pythonmatplotlibseabornscatter-plotline-plot

Seaborn lineplot - connecting dots of scatterplot


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).


Solution

  • 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!