Search code examples
pythonscatter-plotline-plot

How to connect dots in order in a scatter plot?


I want to connect some points to understand the shape of the data. My code is the following

import numpy as np 
import matplotlib.pyplot as plt 
from random import randint, uniform,random
import random
import math

FO_1_NSGA=[1737903,1775238,1745292,1753900,1739432,1765932]
FO_2_NSGA=[1250000,1212665,1235970,1224003,1242687,1216719]
plt.scatter(FO_1_NSGA,FO_2_NSGA,marker='s',c="red",linewidths=True,label="NSGA",edgecolors='blue')
plt.plot(FO_1_NSGA,FO_2_NSGA)
plt.grid()
plt.xlabel("Costo Total de Transporte (CTT)")
plt.ylabel("Costo Total por Demanda Insatisfecha (CDIT)")
plt.legend(loc=0)
plt.show()

The output is the following (which is right)

enter image description here

I want to connect these points to see the exponential decreasing behavior of my variables, but when I try to do that adding the following code

plt.plot(FO_1_NSGA,FO_2_NSGA)

I get this enter image description here

which is clearly not right... any ideas?.


Solution

  • Your datasets are not in ascending or descending order, you need to make sure that when using plt.plot, you have the x-variable in ascending order with the corresponding y-variable in the respective positions. This is because plt.plot will join the dots in the order that it is given, so one must provide the data points in an ascending or descending order.

    Reformat the datasets to:

    F0_1_NSGA = [1737903, 1739432, 1745292, 1753900, 1765932, 1775238]

    F0_2_NSGA = [1212665, 1216719, 1224003, 1235970, 1242687, 1250000]

    This will ensure that both your plt.plot and plt.scatter have the same graph shape.

    Hope that worked :)