如何从 csv 文件绘图,使得一列是数据,另一列是误差线?

如何从 csv 文件绘图,使得一列是数据,另一列是误差线?

如何从 csv 文件中绘制图表及其误差线,其中一列是数据,其后的一列是误差线。请看以下示例。这是 Torbjørn T. 对此的回答问题。

\documentclass{article}
\usepackage{pgfplotstable}
\usepackage{filecontents}
\begin{filecontents*}{mydata.csv}
Row, MethodA, Methoderror, MethodB, MethodBerror
1,       1.2      , 0.05, 0.7, 0.10
2,       0.8      , 0.2,  0.8, 0.15
3,       0.9425   , 0.09, 1.2, 0.07
4,       0.4794   , 0.12, 1.1, 0.086
5,       1.4565   , 0.056,1.5, 0.005
\end{filecontents*}
\pgfplotstableread[col sep=comma]{mydata.csv}\Data


\begin{document}
% if you want to see what the transposed table looks like
%\pgfplotstabletypeset[string type]{\Data}

\begin{tikzpicture}
\begin{axis}[
  xtick=data,
  xticklabels from table={\Data}{colnames}
  ]
\pgfplotsinvokeforeach{1,...,5}{
  % note x expr = \coordindex
  \addplot table[x expr=\coordindex,y index=#1] {\TransposedData};
  % the following to get the legend
  \pgfmathtruncatemacro{\tmpI}{#1-1}
  \pgfplotstablegetelem{\tmpI}{Method}\of\Data
  \addlegendentryexpanded{Method \pgfplotsretval}
}
\end{axis}
\end{tikzpicture}
\end{document}

答案1

根据手册中所述,您可以使用选项指定包含 y 误差的列y error=<column name>table例如\addplot table[x=x,y=y,y error=err] {<table>};

首先,要打开误差线,您需要error bars/y dir=both, error bars/y explicitaxis选项中。

在此处输入图片描述

\documentclass{article}
\usepackage{pgfplotstable}
\usepackage{filecontents}
\begin{filecontents*}{mydata.csv}
Row, MethodA, MethodAerror, MethodB, MethodBerror
1,       1.2      , 0.05, 0.7, 0.10
2,       0.8      , 0.2,  0.8, 0.15
3,       0.9425   , 0.09, 1.2, 0.07
4,       0.4794   , 0.12, 1.1, 0.086
5,       1.4565   , 0.056,1.5, 0.005
\end{filecontents*}
\pgfplotstableread[col sep=comma]{mydata.csv}\Data

\begin{document}
\begin{tikzpicture}
\begin{axis}[
  legend pos=north west,
  xtick=data,
  ybar,
  error bars/y dir=both, % turn on error bars
  error bars/y explicit  % say that error value is given explicitly
  ]

  \addplot table[x=Row,y=MethodA,y error=MethodAerror] {\Data};
  \addlegendentry{Method A}

  \addplot table[x=Row,y=MethodB,y error=MethodBerror] {\Data};
  \addlegendentry{Method B}

\end{axis}
\end{tikzpicture}

% if you want to loop over A and B
\begin{tikzpicture}
\begin{axis}[
  legend pos=north west,
  xtick=data,
  ybar,
  error bars/y dir=both, % turn on error bars
  error bars/y explicit  % say that error value is given explicitly
  ]

  \pgfplotsinvokeforeach{A,B}{
    \addplot table[x=Row,y=Method#1,y error=Method#1error] {\Data};
    \addlegendentry{Method #1}
  }

\end{axis}
\end{tikzpicture}

\end{document}

相关内容