How to start linear regression from (0,1)?
with this resultat
t x
0 1
0.01634 1.2822232
0.04902 1.9517734
0.081699 2.5069444
0.163399 4.0196319
0.245098 5.4139861
0.326797 6.4559171
\documentclass{standalone}
% Required package
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{compat = newest}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin = 0, xmax = 0.5,
ymin = 0, ymax = 11,
width = \textwidth,
height = 0.75\textwidth,
xtick distance = 0.1,
ytick distance = 1,
grid = both,
minor tick num = 1,
major grid style = {lightgray},
minor grid style = {lightgray!25},
xlabel = {Time ($t$)},
ylabel = {Position ($x$)},
legend cell align = {left},
legend pos = north west
]
% Plot data
\addplot[
teal,
only marks
] table[x = t, y = x] {result.dat};
% Linear regression
\addplot[
thick,
orange,
] table[
x = t,
y = {create col/linear regression={y=x}}
] {result.dat};
% Add legend
\addlegendentry{Data}
\addlegendentry{
Linear regression: $ x =
\pgfmathprintnumber{\pgfplotstableregressiona}
\cdot t
\pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$
};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
抱歉,有一段时间忘记了这件事。
这看起来有点奇怪,但对于一次性的事情,你可以这样做
\addplot[thick, black] coordinates {
(0,1)
(0.326797, \pgfplotstableregressionb + 0.326797 * \pgfplotstableregressiona)
};
\addplot
在计算回归线的位置之后。若不绘制实际的回归线,则仅使用draw=none, forget plot
该图的选项。
在下面的代码中我改变了图例条目,因为你画的线实际上不是线性回归。
\documentclass{standalone}
\usepackage{pgfplotstable}
\pgfplotsset{compat = newest}
\pgfplotstableread{
t x
0 1
0.01634 1.2822232
0.04902 1.9517734
0.081699 2.5069444
0.163399 4.0196319
0.245098 5.4139861
0.326797 6.4559171
}\datatable
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmin = 0, xmax = 0.5,
ymin = 0, ymax = 11,
width = \textwidth,
height = 0.75\textwidth,
xtick distance = 0.1,
ytick distance = 1,
grid = both,
minor tick num = 1,
major grid style = {lightgray},
minor grid style = {lightgray!25},
xlabel = {Time ($t$)},
ylabel = {Position ($x$)},
legend cell align = {left},
legend pos = north west
]
% Plot data
\addplot[
teal,
only marks
] table[x = t, y = x] {\datatable};
% Linear regression
\addplot[
draw=none, forget plot
] table[
x = t,
y = {create col/linear regression={y=x}}
] {\datatable};
\addplot[thick, black] coordinates {
(0,1)
(0.326797, \pgfplotstableregressionb + 0.326797 * \pgfplotstableregressiona)};
% Add legend
\addlegendentry{Data}
\addlegendentry{
Linear fit
};
\end{axis}
\end{tikzpicture}
\end{document}