0

I have plotted this data using matplotlib on a log-log plot. I am trying to fit first 5-6 points of my data (low q regime) with a straight line using polyfit . I have tried the solution in this previously answered question. If I try that, curve doesn't even appear on my plot.

enter image description here

Here is my code :

import matplotlib.pyplot as plt
import numpy as np
from scipy import *

with open("data.dat", "r") as f:
x = []
y = []
    for line in f:
        if not line.strip() or line.startswith('@') or line.startswith('#'):
            continue
        row = line.split()
        x.append(float(row[0]))
        y.append(float(row[1]))

x = np.asarray(x)
y = np.asarray(y)

plt.loglog(x, y, basex=10,basey=10,  linestyle="none",marker=".",color='b',label="data")

x_fit= x[:5]
y_fit= 1/x_fit**4/10**6

plt.plot(x_fit,y_fit, label='should be like this',color='r')
m,b = np.polyfit(x_fit, y_fit, 1)
plt.plot(x_fit, m*x_fit+ b, linestyle='--', label='polyfit', color='g')

plt.legend()
plt.ylabel('Spectra ($\AA^2$)')
plt.xlabel('q ($\AA^{-1}$)')
plt.grid()
plt.show()

Edit

If I extract those point in new file and plot it with a normal x-y plot. polyfit works fine.

Community
  • 1
  • 1
Grayrigel
  • 3,474
  • 5
  • 14
  • 32

1 Answers1

0
  • you want a fit on the np.log10(x) not on x, that is why it work on linear scale and not on log scale.
  • you want log10(y) = m* log(x) + b

    m,b = np.polyfit( np.log10(x[:5]), np.log10(y[:5]), 1)
    
  • and according to your red curve (y_fit= 1/x_fit ** 4/10**6), you can find by hand:

    m = -4, b = -6
    
N.G
  • 367
  • 4
  • 10