I have been trying to plot a trendline for a data set of 161 mean temperature values which I imported from Excel with the help of pandas. But I can't manage to create a trendline for the data set. I've followed tutorials on YouTube and other sites, but it doesn't work. I do not get a trend line no matter what I do. I've tried something like this:
m, b = polyfit(data.Year, data.January, 1)
fit = m*(data.Year) b
plt.plot(data.Year, fit)
This method doesn't do anything. I'd love some help to fix this problem, thank you.
CodePudding user response:
An alternate method using the newer
CodePudding user response:
If you're using matplotlib
, you can use polyfit
to generate a trendline:
import matplotlib.pyplot as plt
import numpy as np
# create sample data
xdata = np.array([0,1,2,3,4,5,6,7,8,9])
ydata = np.array([0,1,2,2.5,3.5,4,5,5.5,6,7])
# calculate polynomial
z = np.polyfit(xdata, ydata, 1)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(xdata[0], xdata[-1], 50)
y_new = f(x_new)
plt.plot(xdata, ydata, 'o', x_new, y_new)
plt.xlim([xdata[0]-1, xdata[-1] 1])
plt.show()