28
\documentclass{article}
\usepackage{tikz}
\usepackage{color}
\usepackage[active,pdftex,tightpage]{preview}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
xlabel=Weight (kg), % label x axis
ylabel=Height (cm), % label y axis
axis lines=left, %set the position of the axes
xmin=40, xmax=105, % set the min and max values of the x-axis
ymin=150, ymax=200, % set the min and max values of the y-axis
]
% add main points
\pgfmathsetseed{1138} % set the random seed
\addplot[only marks, samples=30, domain=42:100] % show marks, set no. of samples and set the domain of the points
{(0.6*x+130)+5*rand}; % equation of the points

\end{axis}

\end{tikzpicture}
\end{document}

1 Answer 1

30

PGFPlots can calculate the regression line only for tabulated data, so you'll have to create the points in a table. You can do this using \pgfplotstablenew.

The coefficients of the regression line are stored in the macros \pgfplotstableregressiona and \pgfplotstableregressionb.

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\pgfmathsetseed{1138} % set the random seed
\pgfplotstableset{ % Define the equations for x and y
    create on use/x/.style={create col/expr={42+2*\pgfplotstablerow}},
    create on use/y/.style={create col/expr={(0.6*\thisrow{x}+130)+5*rand}}
}
% create a new table with 30 rows and columns x and y:
\pgfplotstablenew[columns={x,y}]{30}\loadedtable



\begin{tikzpicture}
\begin{axis}[
xlabel=Weight (kg), % label x axis
ylabel=Height (cm), % label y axis
axis lines=left, %set the position of the axes
xmin=40, xmax=105, % set the min and max values of the x-axis
ymin=150, ymax=200, % set the min and max values of the y-axis
clip=false
]

\addplot [only marks] table {\loadedtable};
\addplot [no markers, thick, red] table [y={create col/linear regression={y=y}}] {\loadedtable} node [anchor=west] {$\pgfmathprintnumber[precision=2, fixed zerofill]{\pgfplotstableregressiona} \cdot \mathrm{Weight} + \pgfmathprintnumber[precision=1]{\pgfplotstableregressionb}$};
\end{axis}

\end{tikzpicture}
\end{document}
2
  • Is it possible to get the formula for the regression line from pgfplots and add it to the diagram or do I have to calculate it with another program and add it manually?
    – Philipp
    Jun 14, 2013 at 18:32
  • 3
    @Philipp: The coefficients are stored in two macros that you can access to print the equation. I've edited my answer to show how.
    – Jake
    Jun 14, 2013 at 18:47

You must log in to answer this question.

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