7

Edit: I can't delete this question despite it being based on a silly mistake. Please don't waste time reading/answering.


I'm trying to draw a row of boxes which alternate colours, and I'm using a \foreach to do it. My question is whether it's possible to use colour names as a variable in a foreach loop.

MWE:

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

  \foreach \x/\y {1/blue, 2/red, 3/blue, 4/red}
    \fill[color=\y] (\x,0) --++ (1,0) --++ (0,1) --++ (-1,0) --cycle;

\end{tikzpicture}
\end{document}

When I run this I get the error ! Package pgfkeys Error: I do not know the key '/pgf/foreach/color', to which you passed '\y ', and I am going to ignore it. Perhaps you misspelled it.

In other questions I've seen (example 1, example 2, example 3), people have been asking about defining colours with numbers (red!50!black, for example), so I think this question is different.

So, am I just doing something wrong, or is it simply not possible to do what I'm trying to do. If it's the latter, I'll do it a different way, but I wanted to know about the possibility.

thosphor
  • 1,193
  • 1
  • 12
  • 24
  • 2
    Haha, I usually find this SE forum to have the nicest community! When someone makes a silly mistake on others like SO they'll get downvoted and then forced to delete their post. – MCMastery May 28 '18 at 01:45

2 Answers2

11

\foreach \x/\y in {..}. You forgot in.

By the way, it's a bit shorter with rectangle:

enter image description here

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

  \foreach \x/\y in {1/blue, 2/red, 3/blue, 4/red}
    \fill[color=\y] (\x,0) rectangle +(1,1);

\end{tikzpicture}
\end{document}
Torbjørn T.
  • 206,688
7

A slightly different approach:

  • you don't need color= in your fill command

  • maybe a single loop while counting another variable is simpler


\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\foreach \y [count=\x] in {blue, red, blue, red} {
  \fill[\y] (\x,0) --++ (1,0) --++ (0,1) --++ (-1,0) --cycle;
}

\end{tikzpicture}
\end{document}