21

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

5
  • 5
    For a linear regression see Section 4.22 of the pgfplots manual. Commented Feb 16, 2011 at 20:21
  • Of course, how could I have missed that? Didn't find anything in the scatter plot section. Commented Feb 16, 2011 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
    Commented Feb 16, 2011 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
    Commented Feb 16, 2011 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
    Commented Feb 16, 2011 at 20:35

1 Answer 1

22

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}

\pgfplotstableread{
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};
\addplot [thick, red] table[
    y={create col/linear regression={y=Y}}
] % compute a linear regression from the input table
{\datatable};
\addlegendentry{$y(x)$}
\addlegendentry{%
$\pgfmathprintnumber{\pgfplotstableregressiona} \cdot x
\pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$}
\end{axis}
\end{tikzpicture}
\end{document}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .