Search code examples
pythongraphmatplotlib

Draw a curve from the scatter plot in matplotlib in Python?


enter image description here

My Question:

How can i draw a curve though this data, thus describing an equation for this plot..

I generated this scatter plot by following code, but I am not able to figure out how to generate an equation for this data and draw the corresponding curve on this plot simultaneously. Please Help.!

def draw(data,xlabel,ylabel):
    print('length of data : ',len(data))
    x,y = [],[]
    for i in data:
        x.append((i[1]))
        y.append((i[0]))
    plt.scatter(x, y,marker=r'o',color='b')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.show()

Basically I want something like this:enter image description here


Solution

  • You have to perform a curve fitting procedure, which is called a regression problem in mathematics. In your case it seems that data is more or less exponential, but you can fit arbitrary function through scipy.optimize.curve_fit

    http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html