# Use pgfplots to force linear regression through origin/zero

I'm using pgfplots to make a linear regression of some data. I know the curve should pass through zero (Hookes law).

data.csv:

F,delta
2.4525,0.6
4.905,1.05
7.3575,1.5
9.81,2.4
12.2625,2.5
14.715,3.35
17.1675,4
19.62,4.85
24.525,6.35
29.43,7.85
34.335,10.85
39.24,11.85
44.145,15.85
49.05,17.25
53.955,21.25


latexfile:

\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pagestyle{plain}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
width=\linewidth, % Scale the plot to \linewidth
]
table[x=F,y=delta,col sep=comma, only marks] {data.csv};
table[x=F,y={create col/linear regression={y=delta}}, col sep=comma] {data.csv};
\legend{Metingen,Lineaire regressie: $\delta=\pgfmathprintnumber{\pgfplotstableregressiona} \cdot F$}
\end{axis}
\end{tikzpicture}
\end{document}


How can I force the linear regression to pass through the origin?

You can use gnuplot as a backend to fit the function, similar to the approach given in Adding values to pgfplot legend. That approach has the advantage of letting you fit arbitrary functions, and of being much faster than the pure PGFPlots approach. It has the drawback of requiring a working installation of gnuplot, and having to compile with shell escape turned on.

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}

\begin{filecontents}{data.csv}
F,delta
2.4525,0.6
4.905,1.05
7.3575,1.5
9.81,2.4
12.2625,2.5
14.715,3.35
17.1675,4
19.62,4.85
24.525,6.35
29.43,7.85
34.335,10.85
39.24,11.85
44.145,15.85
49.05,17.25
53.955,21.25
\end{filecontents}

\begin{document}
\begin{tikzpicture}

\begin{axis}[xmin=0, ymin=0, legend pos=north west]

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

\addplot+[raw gnuplot, red, mark=none, smooth] gnuplot {
f(x)=a*x;
% let gnuplot fit, using column 1 and 2 of the data file
% using the following initial guesses
a=1;
set fit errorvariables;
set datafile separator ",";
fit f(x) 'data.csv' using 1:2 via a;
% Next, plot the function and specify plot range
% The range should be approx. the same as the test.dat x range
plot [x=0:55] f(x);
set print "parameters.dat"; % Open a file to save the parameters into
print a, a_err; % Write the parameters to file
};
$y=\pgfmathprintnumber{\paramA} \cdot x$

• Thank you. It's a beautiful solution. I already used gnuplot for plotting a NACA2412 airfoil in that document, so gnuplot isn't any problem :) Mar 14, 2015 at 18:00