2
\newcommand{\LinReg}[4]{
  \addplot table[mark=none, y={create col/linear regression={y=#3}}] {#4};
  \addplot[only marks, mark size=0.7, x index = #1, y index = #2] table {#4};

  \addlegendentry{%
  $\pgfmathprintnumber[precision=2]{\pgfplotstableregressiona} \cdot x
   \pgfmathprintnumber[precision=2,print sign]{\pgfplotstableregressionb}$} %
}

Im trying to make a macro that simply gives me a plot with data from a csv file including a linear regression. I looked around for inspiration here, but i can't seem to finde anything simple?

One thing i want. It is to specify which column is X value, and which is Y by either index or name (With whitespace). The data is read from something like this:

\pgfplotstableread[col sep=comma]{Data/kanthal-lang.csv}\KanthalLang

Is that possible?

1 Answer 1

1

Do you mean something like the following? (I think now it will be easy for you to adapt it using column names instead of the indices.)

    \begin{filecontents}{kanthal-lang.csv}
        % a,1,2,-0.5
        % b,1,-1,8
        x,y1,y2,y3
        0,1,-1,8.0
        1,2,1,7.5
        2,3,3,7.0
        3,4,5,6.5
        4,5,7,6.0
        5,6,9,5.5
    \end{filecontents}
\documentclass[border=5pt]{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
    \pgfplotsset{
        compat=1.14,
    }
\newcommand{\LinReg}[3]{
    \addplot+ [
        only marks,
        mark size=0.7,
        % to not advance the cycle list and to not create a legend entry
        forget plot,
    ] table [
        x index=#1,
        y index=#2,
    ] {#3};
    \addplot+ [
        mark=none,
    ] table [
        x index=#1,
        y={create col/linear regression={y=[index]#2}},
    ] {#3};

    \addlegendentryexpanded{%
        $\pgfmathprintnumber[precision=2]{\pgfplotstableregressiona} \, x
        \pgfmathprintnumber[precision=2,print sign]{\pgfplotstableregressionb}$%
    }
}
\begin{document}
    \begin{tikzpicture}
            \pgfplotstableread[col sep=comma]{kanthal-lang.csv}\KanthalLang
        \begin{axis}
            \LinReg{0}{1}{\KanthalLang}
            \LinReg{0}{2}{\KanthalLang}
            \LinReg{0}{3}{\KanthalLang}
        \end{axis}
    \end{tikzpicture}
\end{document}

image showing the result of above code

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .