Nova Venandi
Nova Venandi

Reputation: 1

How do you plot a trendline for a dataset imported from Excel?

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.

Upvotes: 0

Views: 154

Answers (2)

cfort
cfort

Reputation: 2776

An alternate method using the newer numpy.polynomial package might be easier to read:

import matplotlib.pyplot as plt
from numpy.polynomial import Polynomial

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])

poly_fit = Polynomial.fit(xdata, ydata, 1)

plt.plot(xdata, ydata, 'o', *poly_fit.linspace())

enter image description here

Upvotes: 1

Sh_gosha
Sh_gosha

Reputation: 111

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()

Upvotes: 0

Related Questions