Pgfplots offers the possibility to compute a linear regression, as in the following post Linear regression - trend line with pgfplots .

However, is it possible to compute the mean square error ?

My first idea would be to create a new column with the square error and then compute the mean. But is it possible to do it inside pgfplots ?


You can calculate the regression line in a new column of your table, and then calculate the (square) error from that:




\pgfmathsetseed{1138} % set the random seed
\pgfplotstableset{ % Define the equations for x and y
    create on use/x/.style={create col/expr={42+5*\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:

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

% Calculate the errors
    create col/expr={\thisrow{y}-\thisrow{regression}}

% Calculate the average squared error
Mean squared error: \meansquarederror


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

\addplot [only marks] table {\loadedtable};
\addplot [no markers, thick, red,
    error bars/.cd,
        y dir=plus,
        y explicit,
        draw error bar/.code 2 args={
        \fill ##1 rectangle \expression;
    ] table [y=regression, y error expr=\thisrow{error}] {\loadedtable} node [anchor=west] {$\pgfmathprintnumber[precision=2, fixed zerofill]{\pgfplotstableregressiona} \cdot \mathrm{Weight} + \pgfmathprintnumber[precision=1]{\pgfplotstableregressionb}$};

| improve this answer | |
  • Looks good ! Actually I wanted to compute only the mean square error, so I will adapt your solution in tex.stackexchange.com/questions/62409/… to your current post. – Laurent Dudok de Wit Nov 27 '13 at 22:51
  • @Laurent: Ah, yes, sorry, I missed the "mean". I've added an approach for calculating the mean squared error using \pgfplotstableforeachcolumnelement – Jake Nov 27 '13 at 23:05
  • @ Jake, this is a great and elegant solution (no transpose needed), thanks ! – Laurent Dudok de Wit Nov 28 '13 at 0:48

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.