Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I am trying to draw colored lines with a foreach loop. The command I use to draw the line creates a colored line if I use it standalone. Once I put it inside the foreach loop, I only get a black line. How do I draw colored lines inside a foreach loop?

\documentclass{report}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[lengthMark/.style={<->}]
    \foreach \i/\color in {0/{violet!50},1/yellow} {
        \draw[\color] (3.5, -.25-\i) -- ++(.5, 0);
        \draw[red] (0,0) --(2,2);
    }
\draw[red] (0,0) --(2,-2);
\end{tikzpicture}
\end{document}

write latex, note while posting it only the line drawn outside the foreach (\draw[red] (0,0) --(2,-2);) appears colored.

share|improve this question
1  
\color is an important macro for xcolor. And inside \foreach you overwrite it. I've changed it to \mycolor in writelatex. Can you confirm if that is what you want? –  percusse Sep 3 '13 at 22:03
    
@percusse: confirmed, I already accepted gonzolas awnser –  ted Sep 3 '13 at 22:09
add comment

1 Answer

up vote 7 down vote accepted

Use a different name instead of \color; in general, I always try to avoid using names which correspond to already defined commands:

\documentclass{report}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
    \foreach \i/\colora in {0/{violet!50},1/yellow} {
        \draw[\colora] (3.5, -.25-\i) -- ++(.5, 0);
        \draw[red] (0,0) --(2,2);
    }
\draw[red] (0,0) --(2,-2);
\end{tikzpicture}
\end{document}

enter image description here

share|improve this answer
1  
Actually, also \i is defined. But if no strange text is involved, it shouldn't be a problem like using \color. –  egreg Sep 3 '13 at 22:08
    
@egreg tex.stackexchange.com/questions/47595/… :P –  percusse Sep 3 '13 at 22:10
    
@egreg:that is good to know. But as I just saw per percusses link, you have the same habit of using i as a loop index ;). Is there a way to test if a name is free? –  ted Sep 3 '13 at 22:12
    
@ted If iota is not required then you can use it in the loop via overwriting it but \color is essential to TikZ. –  percusse Sep 3 '13 at 22:14
    
@percusse: the essential part I learned the hard way, thus my comment if there is a way to check if i overwrite something (I believe e.g. newcommand disallows overwriting for this reason), and since I am no latex guru (I had no need to use \color yet) I overlook these things... –  ted Sep 3 '13 at 22:19
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.