0

I have a file contains x, y, and y-err and I simply want to fit a straight line to these data.

This is my original code which I'm plotting the data. based n this I want to fit the straight line:

import numpy as np
import matplotlib.pyplot as plt

#read the data file
Data = np.loadtxt('dmvals.dat')    
MJD = Data[:,0]    
DM = Data[:,1]    
DM_err = Data[:,2]    
font = {'family': 'serif',
        'color':  'blue',
        'weight': 'normal',
        'size': 14,
        }

plt.figure()    
plt.xlabel('time[MJD]', fontdict=font)    
plt.ylabel('DM[pc/cm^3]', fontdict=font)    
plt.title('DM values', fontdict=font)    
plt.errorbar(MJD, DM, DM_err,color='magenta')    
plt.subplots_adjust(left=0.15 , hspace = 0.5)    
plt.savefig('dm_variations_plot.png')
dportman
  • 1,101
  • 10
  • 20
  • Possible duplicate of [Linear regression with matplotlib / numpy](https://stackoverflow.com/questions/6148207/linear-regression-with-matplotlib-numpy) – OriolAbril May 10 '18 at 21:15

1 Answers1

1

The easiest way is to use numpy.polyfit to fit a 1st degree polinomial:

p = numpy.polyfit(MJD, DM, deg=1)

p will be a list containing the intercept and the slope of the fit line

You can then plot the line on your data using

x = MJD
y = p[1] + p[0] * MJD
plt.plot(x, y, '--')
dportman
  • 1,101
  • 10
  • 20
  • Thanks, @dportman : ) In my script, I'm using plt.errorbar to plot the data and I'm a bit confused with what you gave me. it didn't give me what I need when included your answer with what I have, it also complains about the length of the axes. any further explanations? – abubakr yagob May 10 '18 at 20:43
  • I edited my answer so it is more suited for your code. You can call plt.plot right after you call plt.errorbar and it will add the line plot on top of your existing errorbar plot. – dportman May 10 '18 at 21:00
  • It works well, thanks! Just for the reference, the correct is x = MJD instead of x = MD and the same for y – abubakr yagob May 10 '18 at 21:28
  • Cool, glad to hear! I will edit the post. Please accept the answer. – dportman May 11 '18 at 02:53
  • I tried but I think my reputation doesn't allow me yet. – abubakr yagob May 11 '18 at 09:04