2

I've been trying to fit some data to the best fit line for a specific set x and y. I tried unsucessfully many times, and I cant seem to find a way to fit the data using yscale('log') and xscale('log'). I get this weird result but I can't seem to find why it is giving this strange [result]

[result]:https://www.dropbox.com/s/g6m4f8wh7r7jffg/Imagem%20sem%20t%C3%ADtulo.png?dl=0 .

My code:

#!/usr/bin/env python 
# import the necessary modules
import numpy as np
import matplotlib.pyplot as plt

# Generate x and y values which the curve will be fitted to
# (In practical cases, these should be read in)
x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
y = [497775, 150760, 50929, 19697, 8520, 3948, 1812, 710, 214, 57, 18, 4]

p = np.polyfit(x,y,1) 
plt.plot(x, np.polyval(p,x), 'r-')
plt.plot(x, y)
plt.yscale('log')
plt.xscale('log')
plt.show()

I have a hunch that it is because I am using polyvals, but I can´t find how to calculate it for logarithms. Can you help? I am new to this and I need help!

  • Could you please elaborate on what that means? There is nothing inherently special about plotting fitted data on a logarithmic scale. Do you need the logarithmic nature to somehow influence the fit? – Carsten Mar 23 '15 at 23:21
  • I just can´t plot the fit line for a logaritmic scale!! – Grupo ProjectGEODEV Mar 23 '15 at 23:28

1 Answers1

1

Something that appears linear on a log-log plot is not a linear function, it's an exponential function.

You're getting the best fit line:

y = a * x + b

but what you want is the best fit exponential function of the form:

y = a * x**k

There are a number of ways to do this. Using polyfit is a good approach, but you'll need to fit the line in "log space". In other words, fit a line of logarithm of x to the logarithm of y.

For example, based on your code:

import numpy as np
import matplotlib.pyplot as plt

x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
y = [497775, 150760, 50929, 19697, 8520, 3948, 1812, 710, 214, 57, 18, 4]

logx, logy = np.log(x), np.log(y)

p = np.polyfit(logx, logy, 1)
y_fit = np.exp(np.polyval(p, logx))

plt.plot(x, y_fit, 'r-')
plt.plot(x, y)
plt.yscale('log')
plt.xscale('log')
plt.show()

enter image description here

Joe Kington
  • 275,208
  • 71
  • 604
  • 463