使用变量绘制 tikz 图

使用变量绘制 tikz 图

我找到了自己的命令来用 tikz 绘制图表。

我更愿意向命令传递数字而不是常数值来决定图表中条形的高度。

问题: 我使用了错误的语法,因此 Tex 无法解析我的参数来设置条形高度。我尝试了 a、#a、{#a} 和 #{a},但目前没有任何效果。

问题:我的错误是什么?如何解决?

\newcommand{\clocksTen}[a][b][c][d]{
\begin{tikzpicture}
%  \centering
\begin{axis}[
ybar,
enlargelimits=0.15,
legend style={at={(0.5,-0.15)},
anchor=north,legend columns=-1},
%width=0.4\textwidth,
ylabel={CPU clocks},
symbolic x coords={one, two, three, four},
xtick=data,
nodes near coords,
nodes near coords align={vertical},
]
\addplot coordinates {
(one, a) %doesnt work
};
\addplot coordinates {
(two, #a) %doesnt work
};
\addplot coordinates {
(three, {#a}) %doesnt work
};
\addplot coordinates {
(four, #{a}) %doesnt work
};
\legend{one, two, three, four}
\end{axis}
\end{tikzpicture}
}

答案1

LaTeX 参数始终是数字,前面有一个井号,例如#1。您需要在方括号中提供所需参数的数量(稍后在花括号内输入)\newcommand。单个可选参数的默认值(始终#1)可以跟在另一对方括号中,并且在使用时也放在方括号内。

\documentclass{minimal}
\usepackage{tikz}
\usepackage{pgfplots}

\newcommand{\clocksTen}[4]{
\begin{tikzpicture}
\begin{axis}[
  ybar,
  enlargelimits=0.15,
  legend style={at={(0.5,-0.15)},
  anchor=north,legend columns=-1},
  ylabel={CPU clocks},
  symbolic x coords={one, two, three, four},
  xtick=data,
  nodes near coords,
  nodes near coords align={vertical},
]
\addplot coordinates {(one, #1)};
\addplot coordinates {(two, #2)};
\addplot coordinates {(three, #3)};
\addplot coordinates {(four, #4)};
\legend{one, two, three, four}
\end{axis}
\end{tikzpicture}
}
\begin{document}

\clocksTen{2}{4}{8}{16}

\end{document}

PS:请始终将文档类和必要的包添加到您的 MWE,以使其真正发挥作用。

相关内容