Example: Regression with Residuals

Published 2014-03-20 | Author: Jake

We will draw a regression line through some points, as in http://pgfplots.net/tikz/examples/regression-line/ . This time, we will implement a style for negative and positive residuals using an optional argument.

This code was written by Jake on TeX.SE.

Download as: [PDF] [TEX]  •  [Open in Overleaf]

Regression with Residuals

Do you have a question regarding this example, TikZ or LaTeX in general? Just ask in the LaTeX Forum.
Oder frag auf Deutsch auf TeXwelt.de.

\pgfmathsetseed{10} % 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)+8*rand}}
% create a new table with 30 rows and columns x and y:

% Calculate the regression line
\pgfplotstablecreatecol[linear regression]{regression}{\loadedtable}

    colored residuals/.style 2 args={
        only marks,
        point meta=explicit,
        colormap={redblue}{color=(#1) color=(#2)},
        error bars/y dir=minus,
        error bars/y explicit,
        error bars/draw error bar/.code 2 args={
                \draw [#2] ##1 -- ##2;
                \draw [#1] ##1 -- ##2;
            meta expr=(\thisrow{y}-\thisrow{regression})/abs(\thisrow{y}-\thisrow{regression}),
            y error expr=\thisrow{y}-\thisrow{regression}
    colored residuals/.default={red}{blue}
\begin{tikzpicture}[every node/.style={font=\sffamily}]
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
  tick label style = {font=\sansmath\sffamily},
  every axis label = {font=\sansmath\sffamily},
  legend style = {font=\sansmath\sffamily},
  label style = {font=\sansmath\sffamily},

\addplot [colored residuals] table {\loadedtable};
\addplot [
    no markers,
    thick, black
] table [y=regression] {\loadedtable} ;



Adding comments is currently not enabled.