# pgfplots/gnuplot: How to find the curve-fitting function passing through certain points and plot it?

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}
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 • Like this? tex.stackexchange.com/questions/57582/… – percusse Nov 25 '16 at 7:59
• @percusse I am not sure, but I need the trendline to be a unique curve (X=[0,5]) with its own style and legend entry rather than an extension. – Diaa Nov 25 '16 at 8:03
• what is it to be extrapolated then? if you are looking for the closed form formula for the curve that won't be possible off-the-shelf – percusse Nov 25 '16 at 8:07
• @percusse I think my question is not clear enough, but I need to deduce the fitting equation of the first four points, then use this equation to draw a new curve over Y=[0,20]. – Diaa Nov 25 '16 at 8:08
• @percusse I have revamped my question; you can find my desired output. – Diaa Nov 25 '16 at 13:37

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}

• That's awesome. You saved me a lot. – Diaa Nov 25 '16 at 17:23
• Out of curiosity, is it possible to write the fitting equation of gnuplot on the graph with an arrow pointing to the trendline? – Diaa Nov 25 '16 at 17:29
• See tex.stackexchange.com/questions/29633/… for one way of doing that – Jake Nov 25 '16 at 18:36
• Many thanks, if you don't mind, I have another question. Why can'tgnuplot read the data from .csv file unlike in case of .dat or .txt file? is it possible to let it read a .csv file? – Diaa Nov 25 '16 at 18:43
• Glad I could help. Good luck with your work! – Jake Nov 25 '16 at 19:06