[Tex/LaTex] Pgfplots: Error of Linear Regression


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:


1 3
2 5
3 4
4 8
5 9
6 8
7 10
8 12
9 10
10 11



    legend pos=north west,
    axis x line*=bottom,
    axis y line*=left,
    tick label style={font=\small},
    tick align=outside, 
    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 {
    % let gnuplot fit, using column 1 and 2 of the data file
    % using the following initial guesses
    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}$    


    dec sep align,
        column name=Parameter Value
        column name=Standard Error