pgfplots:将回归线延伸到表格点之外

pgfplots:将回归线延伸到表格点之外

如何延长在 中绘制的回归线pgfplots?我想将线延长至略低于绘图边界顶部且略高于绘图边界底部的位置。

在此处输入图片描述

\documentclass[tikz]{standalone}

\usepackage{pgfplots}
\usepackage{pgfplotstable}
\pgfplotsset{compat = 1.11}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    grid = major,
    xmin = -2,
    xmax = 4,
    ymin = -2,
    ymax = 4,
    xlabel = {$x$},
    ylabel = {$y$},
    legend pos = outer north east
    ]
    \addplot[only marks, red] table {
      X Y
      0 0
      1 1
      2 2
      2 3
    };
    \addplot[no marks] table [
    y = {create col/linear regression = {y = Y}}
    ]
    {
       X Y
       0 0
       1 1
       2 2
       2 3
     };
     \addlegendentry{$y(x)$}
     \addlegendentry{
       $\pgfmathprintnumber{\pgfplotstableregressiona}\cdot x
       \pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$
     }
  \end{axis}
\end{tikzpicture}
\end{document}

答案1

观察@Peter Grill 的评论,一种解决方法是使用获得的数据并扩展绘图。

\pgfplotstableregressiona*x+\pgfplotstableregressionb

在此处输入图片描述

代码

\documentclass[tikz,border=5pt]{standalone}

\usepackage{pgfplots,filecontents}
\usepackage{pgfplotstable}
\pgfplotsset{compat = newest}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    grid = major,
    xmin = -2,
    xmax = 4,
    ymin = -2,
    ymax = 4,
    xlabel = {$x$},
    ylabel = {$y$},
    legend pos = outer north east
    ]
    \addplot[only marks, red] table {
      X Y
      0 0
      1 1
      2 2
      2 3
    };
    \addplot[no marks] table [
    y = {create col/linear regression = {y = Y}}
    ]
    {
       X Y
       0 0
       1 1
       2 2
       2 3
     };
     \addlegendentry{$y(x)$}
     \addlegendentry{
       $\pgfmathprintnumber{\pgfplotstableregressiona}\cdot x
       \pgfmathprintnumber[print sign]{\pgfplotstableregressionb}$
     }
\addplot[no marks,red,domain=-1:0]{\pgfplotstableregressiona*x+\pgfplotstableregressionb};
\addplot[no marks,red,domain=2:3]{\pgfplotstableregressiona*x+\pgfplotstableregressionb};
  \end{axis}
\end{tikzpicture}
\end{document}

相关内容