3

How am I able to calculate two linear regressions basing on the meta-data?

In my example I want to have one linear regression for the green points and one for the red points.

\documentclass[preview, border={10pt}]{standalone}

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

\begin{filecontents*}{datatable.txt}
one two letter
 9   7   g
 9   6   g
 8   1   g
 7   3   g
 6   5   g
 6   5   g
 5   2   g
 4   8   r
 3   9   r
 3   2   r
 3   1   r
 2   3   r
 1   2   r
\end{filecontents*}

\begin{document}

\centering
\begin{tikzpicture}
\begin{axis}[
    scatter/classes={
        g={mark=*,green},
        r={mark=*,red}
    }
]
\addplot [scatter,only marks,scatter src=explicit symbolic] table [x=one, y=two, meta=letter] {datatable.txt};
\addplot [blue, no markers] table [x=one,y={create col/linear regression={y=two}}] {datatable.txt};
\end{axis}
\end{tikzpicture}

\end{document}
user1
  • 2,196

1 Answers1

2

EDIT:

This can't be done with only pgfplotstable.

See Regression on a portion of the graph with columns (at the beginning), which indicates the regression applies to the whole table. The regression cannot be applied to just part of the table. There is a workaround there that uses gnuplot, but your solution works too.

-- Ross


ORIGINAL ANSWER:

I still don't know, how to do this with only one file, but here is my solution which uses two files

Result:

two linear regression in one image

Code:

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

\usepackage{pgfplotstable}
\pgfplotsset{compat=1.15}

\begin{filecontents*}{datatableA.txt}
one two letter
 9   7   g
 9   6   g
 8   1   g
 7   3   g
 6   5   g
 6   5   g
 5   2   g
\end{filecontents*}

\begin{filecontents*}{datatableB.txt}
one two letter
 4   8   r
 3   9   r
 3   2   r
 3   1   r
 2   3   r
 1   2   r
\end{filecontents*}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
    scatter/classes={
        g={mark=*,green},
        r={mark=*,red}
    }
]
\addplot [scatter,only marks,scatter src=explicit symbolic] table [x=one, y=two, meta=letter] {datatableA.txt};
\addplot [scatter,only marks,scatter src=explicit symbolic] table [x=one, y=two, meta=letter] {datatableB.txt};
\addplot [green, no markers] table [x=one,y={create col/linear regression={y=two}}] {datatableA.txt};
\addplot [red, no markers] table [x=one,y={create col/linear regression={y=two}}] {datatableB.txt};
\end{axis}
\end{tikzpicture}

\end{document}
user1
  • 2,196
  • 1
    See https://tex.stackexchange.com/a/343740, which indicates the regression applies to the whole table. The regression cannot be applied to just part of the table. There is a workaround there that uses gnuplot, but your solution works too. – Ross Sep 04 '17 at 03:42