I want to do linear regression to the data given by x and y. Everything seems to be fine when I use a linear plot, but when I want to plot it on a log scale the line does not look straight. I think I should divide the interval into finer grids rather than only six points. But I couldn’t do that.
How can I do line fitting on a log scale for the below script?
JavaScript
x
21
21
1
import numpy as np
2
import matplotlib.pyplot as plt
3
4
x = np.array([1560., 526., 408., 226., 448., 288.])
5
y = np.array([0.118, 0.124, 0.131, 0.160, 0.129, 0.138])
6
7
f = np.multiply(x,y**2)
8
9
coefs = np.polyfit(x, f, 1)
10
11
pred_f = coefs[1] + np.multiply(sorted(x), coefs[0])
12
13
fig, ax1 = plt.subplots(1, 1, figsize=(8,6))
14
15
ax1.scatter(x, f)
16
ax1.plot(sorted(x), pred_f, 'k--')
17
ax1.set_xscale('log')
18
ax1.set_yscale('log')
19
20
plt.show()
21
Thank you in advance.
Advertisement
Answer
Indeed, “straight lines” (linear functions) don’t look straight on log-log plots:
JavaScript
1
11
11
1
import numpy as np
2
import matplotlib.pyplot as plt
3
4
x = np.linspace(0.1, 10)
5
y = 2*x+3 # LINEAR!
6
7
plt.plot(x, y)
8
plt.xscale('log')
9
plt.yscale('log')
10
plt.show()
11
Result:
To fit on the log scale, run your regression on loagrithms of the original data:
JavaScript
1
10
10
1
coefs = np.polyfit(np.log(x), np.log(f), 1)
2
3
# Now work with logarithms everywhere!
4
pred_f = coefs[1] + np.multiply(sorted(np.log(x)), coefs[0])
5
6
fig, ax1 = plt.subplots(1, 1, figsize=(8,6))
7
ax1.scatter(np.log(x), np.log(f)) # logs here too!
8
ax1.plot(sorted(np.log(x)), pred_f, 'k--') # pred_f is already in logs
9
plt.show()
10
Plot:
Or have Matplotlib draw log ticks. Then you’ll need to exponentiate pred_f
to put it on the same scale as the data:
JavaScript
1
7
1
fig, ax1 = plt.subplots(1, 1, figsize=(8,6))
2
ax1.scatter(x, f) # original scale!
3
ax1.plot(sorted(x), np.exp(pred_f), 'k--') # exponentiate pred_f
4
ax1.set_xscale('log')
5
ax1.set_yscale('log')
6
plt.show()
7
The plot is the same, but it now uses the original scale of your data: