我正在使用 pgfplots 对一些数据进行线性回归。我知道曲线应该通过零点(胡克定律)。
数据.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
latex文件:
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pagestyle{plain}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
width=\linewidth, % Scale the plot to \linewidth
]
\addplot
table[x=F,y=delta,col sep=comma, only marks] {data.csv};
\addplot [no markers]
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}
我怎样才能强制线性回归通过原点?
答案1
您可以将其用作gnuplot
后端来适应该功能,类似于给出的方法向 pgfplot 图例添加值。该方法的优点是可以让你拟合任意函数,而且比纯 PGFPlots 方法快得多。它的缺点是需要安装gnuplot
,并且必须在打开 shell escape 的情况下进行编译。
\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
\addlegendentry{Experiment 1}
\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
};
\addlegendentry[]{\pgfplotstableread{parameters.dat}\parameters % Open the file Gnuplot wrote
\pgfplotstablegetelem{0}{0}\of\parameters \pgfmathsetmacro\paramA{\pgfplotsretval} % Get first element, save into \paramA
$y=\pgfmathprintnumber{\paramA} \cdot x$
}
\end{axis}
\end{tikzpicture}
\end{document}