Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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:

a graph with a line of best fit

share|improve this question
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

1 Answer 1

up vote 12 down vote accepted

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.


\usepackage{pgfplots, pgfplotstable}

1 1
2 4
3 9
4 16
5 25
6 36

\begin{axis}[legend pos=outer north east]
\addplot [only marks, mark = *] table {\datatable};
\addplot [thick, red] table[
    y={create col/linear regression={y=Y}}
] % compute a linear regression from the input table
$\pgfmathprintnumber{\pgfplotstableregressiona} \cdot x
\pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$}
share|improve this answer
This link no longer works. type 'texdoc pdfplots' into your terminal for manual instead. –  Magpie Jan 19 '13 at 16:20

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.