如何在 Tikz 中使用 pgfplots 向随机生成的点添加回归线?

如何在 Tikz 中使用 pgfplots 向随机生成的点添加回归线?
\documentclass{article}
\usepackage{tikz}
\usepackage{color}
\usepackage[active,pdftex,tightpage]{preview}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
xlabel=Weight (kg), % label x axis
ylabel=Height (cm), % label y axis
axis lines=left, %set the position of the axes
xmin=40, xmax=105, % set the min and max values of the x-axis
ymin=150, ymax=200, % set the min and max values of the y-axis
]
% add main points
\pgfmathsetseed{1138} % set the random seed
\addplot[only marks, samples=30, domain=42:100] % show marks, set no. of samples and set the domain of the points
{(0.6*x+130)+5*rand}; % equation of the points

\end{axis}

\end{tikzpicture}
\end{document}

答案1

PGFPlots 只能计算表格数据的回归线,因此您必须在表格中创建点。您可以使用 来执行此操作\pgfplotstablenew

回归线的系数存储在宏\pgfplotstableregressiona和中\pgfplotstableregressionb

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}
\usepackage{pgfplotstable}

\begin{document}

\pgfmathsetseed{1138} % set the random seed
\pgfplotstableset{ % Define the equations for x and y
    create on use/x/.style={create col/expr={42+2*\pgfplotstablerow}},
    create on use/y/.style={create col/expr={(0.6*\thisrow{x}+130)+5*rand}}
}
% create a new table with 30 rows and columns x and y:
\pgfplotstablenew[columns={x,y}]{30}\loadedtable



\begin{tikzpicture}
\begin{axis}[
xlabel=Weight (kg), % label x axis
ylabel=Height (cm), % label y axis
axis lines=left, %set the position of the axes
xmin=40, xmax=105, % set the min and max values of the x-axis
ymin=150, ymax=200, % set the min and max values of the y-axis
clip=false
]

\addplot [only marks] table {\loadedtable};
\addplot [no markers, thick, red] table [y={create col/linear regression={y=y}}] {\loadedtable} node [anchor=west] {$\pgfmathprintnumber[precision=2, fixed zerofill]{\pgfplotstableregressiona} \cdot \mathrm{Weight} + \pgfmathprintnumber[precision=1]{\pgfplotstableregressionb}$};
\end{axis}

\end{tikzpicture}
\end{document}

相关内容