我尝试使用下面的代码迭代颜色数组。目前它只显示一种颜色。
\documentclass{standalone}
\usepackage{tikz}
\newcommand{\colours}{{"00FF00","0000FF","4f81bd","c0504d","9bbb59","8064a2","4bacc6","f79646","0000ff"}}
\begin{document}
\begin{tikzpicture}
\foreach \name [count=\i] in \colours {
\pgfmathsetmacro{\colour}{\colours[\i-1]}
\definecolor{mycolor}{HTML}{\colour}
\fill[mycolor] (\i,0) --++ (1,0) --++ (0,1) --++ (-1,0) --cycle;
}
\end{tikzpicture}
\end{document}
我想要的是显示数组中定义的所有颜色。
#使用 pgfplots 更新
如果将其放入 pgfplots 中,我只会看到图表上绘制了最后一个循环:
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\newcommand{\colours}{{"4f81bd","c0504d","9bbb59","8064a2","4bacc6","f79646","0000ff"}}
\begin{document}
\begin{tikzpicture}[font=\tiny]
\pgfmathsetmacro\num{dim(\colours)}
\begin{axis}[
width = 6cm,
height = 4cm,
ymajorgrids = true,
xmin=0,xmax=8,
ymin=0,ymax=1,
enlarge x limits=.1
]
\pgfplotsinvokeforeach{1,...,\num}{
\pgfmathsetmacro{\i}{int(#1)}
\typeout{ \i }
\pgfmathsetmacro{\colour}{\colours[\i-1]}
\definecolor{mycolor\i}{HTML}{\colour}
\fill[mycolor\i] (axis cs:\i,0) -- (axis cs:{\i+1},0) -- (axis cs:{\i+1},1) -- (axis cs:\i,1) -- cycle;
}
\end{axis}
\end{tikzpicture}
\end{document}
答案1
pgffor
只能看到列表中的一个元素:{...}
。
{}
如果切换到没有列表周围的语法,pgffor 可以看到各个元素:
\documentclass{standalone}
\usepackage{tikz}
\newcommand{\colours}{00FF00,0000FF,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,0000ff}
\begin{document}
\begin{tikzpicture}
\foreach \name [count=\i] in \colours {
\definecolor{mycolor}{HTML}{\name}
\fill[mycolor] (\i,0) rectangle ++(1,1);
}
\end{tikzpicture}
\end{document}
如果你想保留你的语法,你可以在它周围包裹另一个循环,这将“解开”第一层{...}
:
\documentclass{standalone}
\usepackage{tikz}
\newcommand{\colours}{{"00FF00","0000FF","4f81bd","c0504d","9bbb59","8064a2","4bacc6","f79646","0000ff"}}
\begin{document}
\begin{tikzpicture}
\foreach \macro in \colours {
\foreach \name [count=\i] in \macro {
\pgfmathsetmacro{\colour}{\colours[\i-1]}
\definecolor{mycolor}{HTML}{\colour}
\fill[mycolor] (\i,0) --++ (1,0) --++ (0,1) --++ (-1,0) --cycle;
}
}
\end{tikzpicture}
\end{document}
答案2
如果你想保留你的数组,你可以使用以下dim
函数:
\documentclass{standalone}
\usepackage{tikz}
\newcommand{\colours}{{"00FF00","0000FF","4f81bd","c0504d","9bbb59","8064a2","4bacc6","f79646","0000ff"}}
\begin{document}
\begin{tikzpicture}
\pgfmathsetmacro\nbcolours{dim(\colours)}
\foreach \i in {1,...,\nbcolours} {
\pgfmathsetmacro{\colour}{\colours[\i-1]}
\definecolor{mycolor}{HTML}{\colour}
\fill[mycolor] (\i,0) --++ (1,0) --++ (0,1) --++ (-1,0) --cycle;
}
\end{tikzpicture}
\end{document}