# Trend line or line of best fit in pgfplots

Is there an "out of the box" way to automatically draw the trend line in pgfplots?

Below follows a basic illustration of a scatter graph with a line of best fit:

-
For a linear regression see Section 4.22 of the pgfplots manual. – Thorsten Donig Feb 16 '11 at 20:21
Of course, how could I have missed that? Didn't find anything in the scatter plot section. – 0sh Feb 16 '11 at 20:25
Not out of the box, but pgfplots can call gnuplot and you can create a simple script to fit an arbitrary function to your points. This might be more flexible depending on your dataset – Martin H Feb 16 '11 at 20:29
I've always gone with doing the fit myself, then plotting the line using two endpoints (so I can, for example, fix the intercept). Not very elegant, but it works ... – Joseph Wright Feb 16 '11 at 20:31
Some time back I made a little example on how to fit with pgfplots+gnuplot dl.dropbox.com/u/15487093/gnuplot-fit.tex – Martin H Feb 16 '11 at 20:35

Can be achieved using /pgfplots/table/create col/linear regression={⟨key-value-config⟩} documented in Section 4.22 of the pgfplots manual.

Here's a slightly adapted version of the example from the manual. If you want to plot data directly from a file, replace the \datatable in the \addplot command with the file name.

\documentclass{standalone}

\usepackage{pgfplots, pgfplotstable}

X Y
1 1
2 4
3 9
4 16
5 25
6 36
}\datatable

\begin{document}
\begin{tikzpicture}
\begin{axis}[legend pos=outer north east]
\addplot [only marks, mark = *] table {\datatable};
\addlegendentry{$y(x)$}
$\pgfmathprintnumber{\pgfplotstableregressiona} \cdot x \pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$}