![Pgfplots:线性回归误差](https://linux22.com/image/280320/Pgfplots%EF%BC%9A%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E8%AF%AF%E5%B7%AE.png)
希望您不介意我问这个问题,我只是 gnuplot 和 LaTeX 的初学者,但我已经搜索了手册pgfplots
但找不到答案:
是否可以计算并输出两个参数和pgfplots
的线性回归误差(最好在图例中)?我知道 Origin 会自动执行此操作,在 中应该不会太难,但我还没有找到任何东西。a
b
pgfplots
答案1
您可以采用以下方法向 pgfplot 图例添加值:
\documentclass[11pt]{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}
\begin{filecontents}{data.dat}
1 3
2 5
3 4
4 8
5 9
6 8
7 10
8 12
9 10
10 11
\end{filecontents}
\begin{document}
\begin{figure}[h!t]
\centering
\begin{tikzpicture}
\begin{axis}[
legend pos=north west,
axis x line*=bottom,
axis y line*=left,
tick label style={font=\small},
grid=both,
tick align=outside,
tickpos=left,
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 {
f(x)=a*x+b;
% let gnuplot fit, using column 1 and 2 of the data file
% using the following initial guesses
a=1;
b=1;
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}$
}
\end{axis}
\end{tikzpicture}
\end{figure}
\centering
\pgfplotstabletypeset[
dec sep align,
fixed,
columns/0/.style={
column name=Parameter Value
},
columns/1/.style={
column name=Standard Error
}
]{parameters.dat}
\end{document}
答案2
编辑:我错过了您请求打印错误的部分。所以这个答案并没有真正回答问题。
无需使用 gnuplot 即可完成此操作:
\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{
compat=1.9,
legend style={font=\footnotesize}
}
\begin{document}
\pgfplotstableread{
X Y
1 1
2 4
3 3
4 7
}{\datatable}
\begin{tikzpicture}
\begin{axis}[
xlabel={Some xlabel},
ylabel={Some yabel},
legend cell align=left,
legend pos=north west]
\addplot[only marks] table {\datatable};
\addlegendentry{some legend}
\addplot table [y={create col/linear regression={y=Y}}]
{\datatable};
\addlegendentry{%
$\pgfmathprintnumber{\pgfplotstableregressiona} \cdot x
\pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$ lin. Regression} %
\end{axis}
\end{tikzpicture}
\end{document}
代码改编自线性回归 - 使用 pgfplots 绘制趋势线但略有改变。