使用 pgfplots 从 csv 绘制图表?

使用 pgfplots 从 csv 绘制图表?

我正在尝试使用 pgfplots 绘制图表,其中数据是从 CSV 文件中读取的。我的点显示正常,但当我尝试添加回归线时,它在 x=0 处显示为垂直线。有人能告诉我这是怎么回事吗?我的页面是:

\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}

其中 test3.csv 包含(抱歉格式不太规范):

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

该图如下所示:

答案1

您需要一个额外的x = X,,否则它会选择第一列作为 x 坐标。然后它变成

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

结果是

在此处输入图片描述

相关内容