[Tex/LaTex] Pgfplots: Error of Linear Regression

pgfplots

Hope you don't mind me asking this, I'm only a starter at both gnuplot and LaTeX,
but I've already searched the pgfplots manual and couldn't find an answer:

Is it possible to have pgfplots calculate and output the error of its linear regression for both parameters a and b (preferrably in the legend)? I know Origin does this automatically, and it shouldn't be so hard in pgfplots, but I haven't found anything yet.

Best Answer

You can adapt the approach from Adding values to pgfplot legend:

\documentclass[11pt]{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}

\begin{filecontents}{data.dat}
1 3
2 5
3 4
4 8
5 9
6 8
7 10
8 12
9 10
10 11
\end{filecontents}



\begin{document}

\begin{figure}[h!t]
\centering
\begin{tikzpicture}

\begin{axis}[
    legend pos=north west,
    axis x line*=bottom,
    axis y line*=left,
    tick label style={font=\small},
    grid=both,
    tick align=outside, 
    tickpos=left,
    xmin=0, ymin=0
    ]

\addplot[only marks, mark size=1.8, black] file {data.dat};
    % Now call gnuplot to fit this data
    % The key is the raw gnuplot option
    % which allows to write a gnuplot script file
    \addlegendentry[]{Experiment 1}

\addplot+[raw gnuplot, red, mark=none, smooth] gnuplot {
    f(x)=a*x+b;
    % let gnuplot fit, using column 1 and 2 of the data file
    % using the following initial guesses
    a=1;
    b=1;
    set fit errorvariables;
     fit f(x) 'data.dat' using 1:2 via a,b;
         % Next, plot the function and specify plot range
         % The range should be approx. the same as the test.dat x range
     plot [x=0:10] f(x);
    set print "parameters.dat"; % Open a file to save the parameters into
    print a, a_err; % Write the parameters to file
    print b, b_err;
       };       
\addlegendentry[]{\pgfplotstableread{parameters.dat}\parameters % Open the file Gnuplot wrote
    \pgfplotstablegetelem{0}{0}\of\parameters \pgfmathsetmacro\paramA{\pgfplotsretval} % Get first element, save into \paramA
    \pgfplotstablegetelem{1}{0}\of\parameters \pgfmathsetmacro\paramB{\pgfplotsretval}
     $\pgfmathprintnumber{\paramA}\times x + \pgfmathprintnumber{\paramB}$    
}

\end{axis}
\end{tikzpicture}

\end{figure}
\centering
\pgfplotstabletypeset[
    dec sep align,
    fixed,
    columns/0/.style={
        column name=Parameter Value
    },
    columns/1/.style={
        column name=Standard Error
    }
]{parameters.dat}

\end{document}