Gráfico de dispersão com dados de arquivo CSV e linha de tendência

Gráfico de dispersão com dados de arquivo CSV e linha de tendência

Eu criei um gráfico de dispersão com código deesta pergunta anterior.

\documentclass[varwidth=true, border=2pt]{standalone}
\usepackage[utf8]{inputenc} % this is needed for umlauts
\usepackage[ngerman]{babel} % this is needed for umlauts
\usepackage[T1]{fontenc}    % this is needed for correct output of umlauts in pdf
\usepackage[margin=2.5cm]{geometry} %layout  
\usepackage{pgfplots}


\begin{filecontents}{table3.csv}
column 1    column 2
1966    37.51817228
1960    40.56693583
1961    40.71972964
1962    40.97560208
1964    41.11687187
1963    41.25082828
1965    46.02625404
1960    46.22815872
1967    46.67800113
1961    48.39523271
\end{filecontents}


\begin{document}

\begin{tikzpicture}
    \begin{axis}[
            axis x line=middle,
            axis y line=middle,
            enlarge y limits=true,
            %xmin=0, xmax=2150,
            %ymin=0, ymax=600,
            width=15cm, height=8cm,     % size of the image
            grid = major,
            grid style={dashed, gray!30},
            ylabel=steps,
            xlabel=$n$,
            legend style={at={(0.1,-0.1)}, anchor=north}
         ]        
          \addplot[scatter,only marks] table [x=column 1, y=column 2, col sep=comma] {table3.csv};

          %the code below is added via @Peter's comment.
          \addplot[only marks] table [col sep = comma,y={create col/linear regression={y=column 2}}]{table3.csv};


    \end{axis}
\end{tikzpicture}

\end{document}

O gráfico de dispersão fica ótimo, mas quero poder adicionar uma linha de tendência. Todos os exemplos de linhas de tendência que vi foram calculados com dados inseridos diretamente no arquivo .TeX e não em um arquivo .csv.

É possível fazer isso?

Meu outro pensamento foi continuar no Excel, calcular a linha de tendência e depois sobrepor a linha no gráfico. Eu realmente prefiro poder fazer isso de uma forma mais direta, já que meu documento tem muitos gráficos.

editar:Jake me deu ótimas orientações sobre como fazer isso com dados inseridos diretamente no arquivo TeX, mas estou tendo problemas para analisar diretamente do arquivo .csv. Adicionei ao meu código e postei a mensagem de erro que recebo no console.

Com o código adicionado, recebo a mensagem de erro.

./linearreg.tex:30: Package PGF Math Error: Could not parse input '' as a float
ing point number, sorry. The unreadable part was near ''..

A linha 30 do meu documento é a linha adicionada à equação de regressão linear.

edição final:Eu descobri. Este erro foi causado porque meu arquivo tinha colunas com dados em branco. Tive que deletar esses dados em branco para calcular a linha de regressão linear.

Aqui está o mwe final do meu código:

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

\begin{document}
\pgfplotstableread[col sep = comma]{table4.csv}\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
        clip=false
    ]

            \addplot[scatter, only marks] table [x=column 1, y=column 2, col sep=comma] {\loadedtable};
            \addplot[very thick, red] table [col sep = comma,y={create col/linear regression={y=column 2}}]{\loadedtable};

    \end{axis}

\end{tikzpicture}
\end{document}

Responder1

Para obter uma linha de regressão linear para dados de um arquivo de dados, use

\addplot [no markers] table [y={create col/linear regression={y=<column name>}}] {<file name>};

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots, pgfplotstable}
\usepackage{filecontents}

\begin{filecontents}{table.dat}
x y
0 1
100 3
150 2
200 5
300 6
\end{filecontents}

\begin{document}

\begin{tikzpicture}
    \begin{axis}[
            axis x line=middle,
            axis y line=middle,
            enlarge y limits=true,
            width=15cm, height=8cm,     % size of the image
            grid = major,
            grid style={dashed, gray!30},
            ylabel=steps,
            xlabel=$n$,
            legend style={at={(0.1,-0.1)}, anchor=north}
         ]        
        \addplot[only marks] table  {table.dat};
        \addplot [no markers, thick, red] table [y={create col/linear regression={y=y}}] {table.dat};
    \end{axis}
\end{tikzpicture}

\end{document}

informação relacionada