[Tex/LaTex] pgfplots/gnuplot: How to find the curve-fitting function passing through certain points and plot it

curve fittinggnuplotpgfplots

Considering this code, I would like to know how to find the curve-fitting function passing through the first four points (i.e. X=[0,3]) and plot this function (e.g. the red dashed line in the desired output below).

\RequirePackage{luatex85}
\documentclass{standalone}
\usepackage{pgfplots, pgfplotstable}
\pgfplotstableread{%
X Y
0 0
1 1
2 4
3 9
4 12
5 15
}\datatable

\begin{document}
    \begin{tikzpicture}
    \begin{axis}[xmin=0,xmax=5,ymin=0,ymax=20]
    \addplot [only marks, mark = *] table {\datatable};
    \end{axis}
    \end{tikzpicture}
\end{document}

Desired Output

enter image description here

Best Answer

You can use \addplot gnuplot to do the curve fitting using the gnuplot backend, which allows you to use different domains for fitting and plotting the function. It also allows you to fit non-linear functions, like the quadratic function in this example:

\documentclass{standalone}
\usepackage{pgfplots, pgfplotstable}
\usepackage{filecontents}
\begin{filecontents}{data.dat}
X Y
0 0
1 1
2 4
3 9
4 12
5 15
\end{filecontents}

\begin{document}
    \begin{tikzpicture}
    \begin{axis}[xmin=0,xmax=5,ymin=0,ymax=20]
    \addplot [only marks, mark = *] table {data.dat};
    \addplot [no markers, red] gnuplot [raw gnuplot] { % "raw gnuplot" allows us to use arbitrary gnuplot commands
            f(x) = a*x^2 + b;  % Define the function to fit
            a=1; b=1;          % Set reasonable starting values here
            % Select the x-range, the file, the columns (indexing starts at 1) and the variables for fitting
            fit [0:3] f(x) 'data.dat' u 1:2 via a,b; 
            plot [x=0:5] f(x); % Specify the range to plot
    };
    \end{axis}
    \end{tikzpicture}
\end{document}