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

  • 4
    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. – Milo Wielondek 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
  • 2
    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.


\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}$}
| 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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