6

I am trying to plot a graph using pgfplots in which the data is read from a CSV file. My points show up fine, but when I try to add a regression line, it appears as a vertical line at x=0. Can anyone tell me what's going on here? My page is:

\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{siunitx}
\usepackage{graphicx}
\pgfplotsset{compat=1.5}
\title{Test Report}
\author{Joe}
\date{}

\begin{document}

\maketitle

\begin{tikzpicture}
\begin{axis}[title=First LED experiment,
xlabel = Photon frequency,
ylabel = Electron energy,
legend pos = outer north east,
]

\addplot[
    only marks,
    mark = *,
          /pgfplots/error bars/.cd,
        x dir = both,
        y dir = both,
        x explicit,
        y explicit,
]
table [
    x=X,
    y=Y,
    x error=spreadX,
    y error=spreadY,
    col sep=comma,
]
{test3.csv};

\addplot[thick, red] table [
    col sep=comma,
    y = {create col/linear regression={y=Y,x=X}},
]
{test3.csv};

\addlegendentry{Average value}
\end{axis}
\end{tikzpicture}

\end{document}

where test3.csv contains (sorry for the gross formatting):

spreadX,spreadY,maxX,maxY,minX,minY,Y,X
14000000000000.0,0.0,666000000000000.0,3.57e-19,638000000000000.0,3.57e-19,3.57e-19,652000000000000.0
13500000000000.0,2.5e-21,652000000000000.0,3.4e-19,624000000000000.0,3.36e-19,3.38e-19,638000000000000.0
13000000000000.0,2.5e-21,638000000000000.0,3.24e-19,612000000000000.0,3.2e-19,3.22e-19,625000000000000.0
9000000000000.0,1.5e-21,535000000000000.0,2.66e-19,517000000000000.0,2.63e-19,2.65e-19,526000000000000.0
8000000000000.0,1.5e-21,500000000000000.0,2.4e-19,484000000000000.0,2.37e-19,2.39e-19,492000000000000.0
8000000000000.0,3e-21,484000000000000.0,2.33e-19,468000000000000.0,2.27e-19,2.3e-19,476000000000000.0

The graph looks like this:

4

You need an additional x = X, otherwise it picks up the first column as the x coordinates. Then it becomes

\addplot[thick, red] table [
    col sep=comma,
    x = X,% <-- This is new
    y = {create col/linear regression={y=Y,x=X}},
] {test3.csv};

which results in

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.