[Tex/LaTex] Change style of labels of Tikz nodes of a given style

tikz-pgftikz-styles

How can all labels of a given type of node be restyled in Tikz?

Imagine that there are nodes of different styles, and that only the nodes of style X should have red labels. Is this possible without having to change all labels one by one of nodes of style X?

Best Answer

To change it for all nodes:

\tikzset{every node/.style={<style_specs>}}

If you have a custom style, you can set this only for that specific node style:

\tikzset{My Style/.style={red, draw=blue, fill=yellow!20, minimum size=0.5cm}}

If you want to change an existing node style, you can use .append style to add to the nodes style specs:

\tikzset{rectangle/.append style={draw=brown, ultra thick, fill=red!30}}

enter image description here

Code:

\documentclass{article}
\usepackage{tikz}

\tikzset{My Style/.style={red, draw=blue, fill=yellow!20, minimum size=0.5cm}}
\tikzset{rectangle/.append style={draw=brown, ultra thick, fill=red!30}}

\begin{document}
\begin{tikzpicture}
    \node [My Style] at (0,0) {$x$};
    \node [My Style] at (1,0) {$y$};

    \node [rectangle] at (2,0) {$z$};
\end{tikzpicture}
\end{document}

This actual intent here is more complex that what I thought since a label is actually a node. One solution would be to define a style for each particluar shape. So, for instance, for a rectangle you could define My Rectangle as:

\tikzset{My Rectangle/.style={
    rectangle, draw=brown, fill=yellow, thick,
    prefix after command= {\pgfextra{\tikzset{every label/.style={blue}}}}
    }
}

which alters the label style (Again, thanks to percusse):

enter image description here

You could also just change the rectangle style as follows:

\tikzset{rectangle/.append style={
    prefix after command= {\pgfextra{\tikzset{every label/.style={blue}}}}
    }
}

Code:

\documentclass{article}
\usepackage{tikz}

\tikzset{My Rectangle/.style={
    rectangle, draw=brown, fill=yellow, thick,
    prefix after command= {\pgfextra{\tikzset{every label/.style={blue}}}}
    }
}

\begin{document}

\begin{tikzpicture}
    \node [rectangle,    label=black text] at (1,0) {$z$};
    \node [My Rectangle, label={blue text} ] at (3,0) {$z$};
    \node [rectangle, label={blue text} ] at (5,0) {$z$};
\end{tikzpicture}
\end{document}
Related Question