Search code examples
pythonplotrootscatter-plot

Finding Root of a Scatter Plot (Python)


I am currently plotting a hysterisis, out of a data set. It has following form: Image of Hysterisis

The data looks like this:

B(mT)    U (V)   std (V)     direction   loop 
-599.9600   0.2104  0.0019  1.0000  1.0000
-594.9676   0.1994  0.0011  1.0000  1.0000

Now I am trying to find the point of the curve going upwards and the one going downwards, when the voltage is zero. But the value never hits zero explicetly (Just values like 0.0028). So I am searching for ideas, how i can be exact in this case.

Data import:

data1 = genfromtxt(fname="path", delimiter="")
field1 = data1[:,0]
voltage1 = data1[:,1]
std1 = data1[:,2]
direction1 = data1[:,3]
loop1 = data1[:,4] 

Ideas on how to find the root


Solution

  • You can easily find the roots using scipy.interp1d:

    # [x,y] is one of the plotted curves.
    i    = np.argmin(np.fabs(y))  # find point closest to the root
    x, y = x[i-3:i+4], y[i-3:i+4] # make sub-arrays near the root
    x_root = scipy.interp1d(y, x, kind='linear')(0)
    

    Basically, we interpolate a multi-linear curve to the scattered data f(y,x) near y=0, and then we ask what is the x-coordinate where y=0. We use argmin to locate the data points closest to the root itself.

    You can also increase the order of the interpolation from linear to higher order if the scattered data is high-quality.


    PS. Root-finding algorithms can also solve this problem, but they are much more complicated. They need properly-defined convergence tolerances, and they can get stuck in local minima. Our code snippet avoids all those issues in a nice way, and it can still provide high-order accuracy.