我有这个 pgfplots 代码,它从文件中获取数据mydata.tsv
并创建条形图。现在我想将其转换为宏,以便将其用于多个文件。
\pgfplotstableread[col sep=tab]{mydata.tsv}\datatable
\makeatletter
\pgfplotsset{
/pgfplots/flexible xticklabels from table/.code n args={3}{
\pgfplotstableread[#3]{#1}\coordinate@table
\pgfplotstablegetcolumn{#2}\of{\coordinate@table}\to\pgfplots@xticklabels
\let\pgfplots@xticklabel=\pgfplots@user@ticklabel@list@x
}
}
\makeatother
\begin{tikzpicture}
\begin{axis}[
ybar,
ymin=0,
ylabel=\si{\micro\second},
flexible xticklabels from table={mydata.tsv}{stage}{col sep=tab},
xticklabel style={rotate=90, anchor=east},
xtick=data]
\addplot
plot [error bars/.cd, y dir=both, y explicit]
table[x expr=\coordindex, y=mean, y error=error]{\datatable};
\end{axis}
\end{tikzpicture}
在看了一些宏简介,我尝试了这个:
\newcommand{\myplot}[1]{
% same code as above, with "mydata.tsv" replaced by "#1"
}
\myplot{mydata1.tsv}
\myplot{mydata2.tsv}
但是我收到以下错误:
Package pgfplots Error: Sorry, could not retrieve column 'stage' from table '{stage}{mean}{error}@table'.
我假设我的代码中现有的#1
、#2
、存在一些问题,我也尝试用、、 、#3
替换它们,但没有帮助(同样的错误)。##1
##2
##3
编辑:数据如下mydata.tsv
:
stage mean error
One 27.19143 0.274788478838
Two 27.83391 0.354268822434
Three 87.15405 0.437466618964
(以制表符分隔,可能未在 stackexchange 中正确呈现)
答案1
我使用逗号代替制表符,但您可以将其改回来。您不需要在定义中创建键。此外,您的参数定义应该与制表符版本相匹配。可能在您的系统中#2
变成。stage<tab>
\documentclass{article}
\usepackage{pgfplotstable,filecontents,siunitx}
\pgfplotsset{compat=1.9}
\begin{filecontents*}{mydata1.tsv}
stage,mean,error
One,27.19143,0.274788478838
Two,27.83391,0.354268822434
Three,87.15405,0.437466618964
\end{filecontents*}
\makeatletter
\pgfplotsset{%
/pgfplots/flexible xticklabels from table/.code n args={3}{
\pgfplotstableread[#3]{#1}\coordinate@table
\pgfplotstablegetcolumn{#2}\of{\coordinate@table}\to\pgfplots@xticklabels
\let\pgfplots@xticklabel=\pgfplots@user@ticklabel@list@x
}
}%
\makeatother
\newcommand{\myplot}[1]{%
\pgfplotstableread[col sep=comma]{#1}\datatable%
%
\begin{tikzpicture}
\begin{axis}[
ybar,
ymin=0,
ylabel=\si{\micro\second},
flexible xticklabels from table={#1}{stage}{col sep=comma},
xticklabel style={rotate=90, anchor=east},
xtick=data]
\addplot
plot [error bars/.cd, y dir=both, y explicit]
table[x expr=\coordindex, y=mean, y error=error]{\datatable};
\end{axis}
\end{tikzpicture}%
}
\begin{document}
\myplot{mydata1.tsv}
\end{document}