I'm trying to write a script with python/numpy/scipy for data manipulation, fitting and plotting of angle dependent magnetoresistance measurements. I'm new to Python, got the frame code from my PhD advisor, and managed to add few hundred lines of code to the frame. After a while I noticed that some measurements had multiple blunders, and since the script should do all the manipulation automatically, I tried to mask those points and fit the curve to the unmasked points (the curve is a sine squared superposed on a linear function, so numpy.ma.polyfit isn't really a choice). However, after masking both x and y coordinates of the problematic points, the fitting would still take them into consideration, even though they wouldn't be shown in the plot. The example is simplified, but the same is happening;
import numpy.ma as ma
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def Funk(x, k, y0):
return k*x + y0
fig,ax= plt.subplots()
x=ma.masked_array([1,2,3,4,5,6,7,8,9,10],mask=[0,0,0,0,0,0,1,1,1,1])
y=ma.masked_array([1,2,3,4,5,30,35,40,45,50], mask=[0,0,0,0,0,1,1,1,1,1])
fitParamsFunk, fitCovariancesFunk = curve_fit(Funk, x, y)
ax.plot(x, Funk(x, fitParamsFunk[0], fitParamsFunk[1]))
ax.errorbar(x, y, yerr = None, ms=3, fmt='-o')
plt.show()
While writing the post I figured out that I can do this:
def Funk(x, k, y0):
return k*x + y0
fig,ax= plt.subplots()
x=np.array([1,2,3,4,5,6,7,8,9,10])
y=np.array([1,2,3,4,5,30,35,40,45,50])
mask=np.array([0,0,0,0,0,1,1,1,1,1])
fitParamsFunk, fitCovariancesFunk = curve_fit(Funk, x[mask], y[mask])
ax.plot(x, Funk(x, fitParamsFunk[0], fitParamsFunk[1]))
ax.errorbar(x, y, yerr = None, ms=3, fmt='-o')
plt.show()
I guess that scipy curve_fit isn't meant to deal with masked arrays, but I still would like to know whether there is any workaround for this (I need to work with masked arrays because the number of data points is >10e6, but I'm only plotting 100 at once, so I would need to take the mask of the part of the array that I want to plot and assign it to another array, while copying the values of the array to another or setting the original mask to False)? Thanks for any suggestions