# How to get a best-fit line on a scatterplot?

I know that I am supposed to call ListPlot inside of the Show function, but I can't seem to get that to work. The best I can get is this, which has the best-fit line following the scatter plot. How do I get the fit line to display on top of the scatter plot?

theTemps = WeatherData["Grossschwabhausen", "MeanTemperature", {{1956}, {2016}, "Year"}];
GrossschwabhausenTempByYear = Table[theTemps[[i]][[2]], {i, 59}];
ListPlot[miamiTempByYear, Joined -> False, Filling -> Axis,
PlotStyle -> Thick, AxesLabel -> {"Years from 1956", "Celsius"}]
Fit[GrossschwabhausenTempByYear, {1, x}, x]
Plot[%, {x, 2, 59}]
Show[%, {x, 2, 59}]

• You could just do ListPlot[theTemps, AxesLabel -> {"Years from 1956", "Celsius"}, Filling -> Axis]. But, why are you fitting a line to a manifestly nonlinear trend? – J. M. is away Jun 21 '16 at 3:24
• The line does show a trend - 6.400613676212742 + 0.031793103448275836 x. – Masheen Jun 21 '16 at 3:39
• So you really need a picture like this one? – J. M. is away Jun 21 '16 at 3:44
• Yes! That's perfect! How did you do that? – Masheen Jun 21 '16 at 3:47

## 1 Answer

The result returned by WeatherData[] is a TimeSeries[] object. ListPlot[] can deal with it directly, but LinearModelFit[] needs some assistance to handle it, since it cannot directly deal with either TimeSeries[] or Quantity[] objects. Thus:

trendLine = LinearModelFit[theTemps["Path"] // QuantityMagnitude, x, x]

Show[ListPlot[theTemps, AxesLabel -> {"Years from 1956", "Celsius"}, Filling -> Axis],
Plot[trendLine[x], {x, theTemps["FirstTime"], theTemps["LastTime"]}]]


As noted by Jim, you can use DateListPlot to have years on the horizontal axis:

Show[{DateListPlot[theTemps, Joined -> False, Filling -> Axis],
Plot[trendLine[x], {x, theTemps["FirstTime"], theTemps["LastTime"]}]}]


(Note the extended date range as well.)

• You are amazing thank you! – Masheen Jun 21 '16 at 3:52
• When I try to run your code I get this error: LinearModelFit::notdata: The first argument is not a vector, matrix, or a list containing a design matrix and response vector. >> – Masheen Jun 21 '16 at 4:46
• theTemps is the same thing in your question. What exactly did you change inside LinearModelFit[]? (Now that I think about it: what version are you on?) – J. M. is away Jun 21 '16 at 4:47
• Yes, Masheen, @J.M. is amazing. Using DateListPlot would show the year and adding in a plot of the prediction and/or confidence bands would be helpful for interpreting the seriousness of the line (although still not accounting for the likely serial correlation). – JimB Jun 21 '16 at 5:20
• @Jim, maybe you can convince the guy. Admittedly I had forgotten about the possibility of serial correlation, but even with that caveat, I am not seeing a "secular" trend, and was thus skeptical of the need to put in a trend line. – J. M. is away Jun 21 '16 at 5:36