0

The x and y are data lists and plot just fine with a linear trend line.
I would also like to add a cubic trend line.

import matplotlib.pyplot as plt
x = (distanceList)
y = (percentCopper)
plt.scatter(x,y) 
title = "trendLine"
xLabel = "Distance m"
yLabel = "percent copper"
plt.title (title, fontsize=10);
plt.ylabel(yLabel, fontsize=10);
plt.xlabel(xLabel, fontsize=10);
fit = np.polyfit(x,y,1)
fit_fn = np.poly1d(fit) 
plt.plot(x, y, '.', x, fit_fn(x), 'r')
plt.xlim(0, 50)
plt.ylim(0, 2.5)
plt.show()
Tuffwer
  • 1,027
  • 9
  • 23
R Rip
  • 19
  • 3
  • You don't actually have a question here. Exactly which part of adding a cubic trend line are you having trouble with? Do you need to compute the fit, or plot both fit's together or something else entirely? – Tuffwer Mar 21 '17 at 02:18
  • I am suppose to plot a linear fit line and a cubic function – R Rip Mar 21 '17 at 02:20
  • I think this existing question should cover everything you need to add the cubic fit to your plot http://stackoverflow.com/questions/18767523/fitting-data-with-numpy – Tuffwer Mar 21 '17 at 02:32

1 Answers1

2

Just use np.polyfit(x,y,3) and add it to the plot, like in the code below:

import matplotlib.pyplot as plt
import numpy as np
x = np.array(range(50))
y = x**3/5000.0-x/5000.0
plt.scatter(x,y) 
title = "trendLine"
xLabel = "Distance m"
yLabel = "percent copper"
plt.title (title, fontsize=10);
plt.ylabel(yLabel, fontsize=10);
plt.xlabel(xLabel, fontsize=10);
fit = np.polyfit(x,y,1)
fit3 = np.polyfit(x,y,3)
fit_fn = np.poly1d(fit) 
fit_fn3 = np.poly1d(fit3)
plt.plot(x, y, '.', x, fit_fn(x), fit_fn3(x), 'r')
plt.xlim(0, 50)
plt.ylim(0, 2.5)
plt.show()

enter image description here

Miriam Farber
  • 18,986
  • 14
  • 61
  • 76
  • This won't work correctly because the polyfit function returns the list of coefficients to the polynomial for in the reverse order that poly1d expects them to be in. As stated in the top answer to the linked post on my comment on the question you need to reverse that list order, or use the Polynomial function instead of poly1d. – Tuffwer Mar 21 '17 at 16:01
  • @Tuffwer Are you sure? I switched y to be y = x**3/5000.0-x/5000.0 just to make it a bit more complicated, and I attach the plot. It seems like the correct fitting, isn't it? – Miriam Farber Mar 21 '17 at 16:06
  • Well I was... I spent about 15 minutes reading docs last night and swear that's what I read. Re-reading [polyfit](https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html) and [poly1d](https://docs.scipy.org/doc/numpy/reference/generated/numpy.poly1d.html) now though it seems the orders do match and I was completely mistaken. Apologies, have my upvote. – Tuffwer Mar 21 '17 at 16:12