0

I have a graph which I draw with my own command. I have to use that very often but normally in different colors. There are no problems with edges becaus I simply can use \draw[style=green](x)--(y) to color the edge (x,y) green. But I also want to do that with specific nodes e.g: the node v1 should be red.

Here is my command:

\newcommand{\mygraph}{
    \node[](x) at (0,0){$x$};
    \node[](y) at (0,-4){$y$};
    \foreach \a in {1,...,5}{
        \node[](v\a) at (\a*180/6:4) {$v_\a$};
    }
    \foreach \a in {1,...,5}{
        \draw (x)--(v\a);       
    }
}

And how I use it:

\begin{figure}[h]
    \centering
    \begin{tikzpicture}
        \mygraph
        \draw[dotted](x)--(y);
        \draw[style=green](x)--(v1);
    \end{tikzpicture}
    \caption{Graph $G$}
\end{figure}

So is there a possibility to take one of the nodes and recolor it?

  • 1
    Please add a minimal working example. – AndréC Aug 29 '19 at 14:52
0

If you always have 5 nodes/path, you could define a command with optional and default arguments using the xparse parckage.

\documentclass[tikz,border=3mm]{standalone}
\usepackage{xparse}
\begin{document}
% This defines the \mygraph macro with default black colours for all node/path pair
% but you can cutsomize colours on the fly !
\NewDocumentCommand{\mygraph}{ O{black} O{black} O{black} O{black} O{black}}{
    \node[](x) at (0,0){$x$};
    \node[](y) at (0,-4){$y$};
    \foreach \a/\mycolor in {1/#1,2/#2,3/#3,4/#4,5/#5}{
        \node[\mycolor](v\a) at (\a*180/6:4) {$v_\a$};
        \draw[\mycolor] (x)--(v\a);       
    }
}
\begin{tikzpicture}
    \mygraph
\end{tikzpicture}
\begin{tikzpicture}
    \mygraph[red][][blue]
\end{tikzpicture}
\end{document}

enter image description here

2

You can store the colors in an array, which get used in the loop.

\documentclass[tikz,border=3mm]{standalone}
\begin{document}
\newcommand{\mygraph}{
    \node[](x) at (0,0){$x$};
    \node[](y) at (0,-4){$y$};
    \foreach \a in {1,...,5}{
        \pgfmathsetmacro{\mycolor}{{\lstColors}[\a-1]}
        \node[\mycolor](v\a) at (\a*180/6:4) {$v_\a$};
    }
    \foreach \a in {1,...,5}{
        \pgfmathsetmacro{\mycolor}{{\lstColors}[\a-1]}
        \draw[\mycolor] (x)--(v\a);       
    }
}
\edef\lstColors{"red","green","blue","orange","magenta"}
\begin{tikzpicture}
 \mygraph
\end{tikzpicture}
\end{document}

enter image description here

  • Thank @Schodinger ! So this is simple way to store array of texts, numbers – Black Mild Aug 30 '19 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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