# How can I set a tikz-node's anchor using a variable?

The following code works as expected.

\documentclass[tikz,margin=1em]{standalone}
\usetikzlibrary{math}
\begin{document}
\begin{tikzpicture}[scale=3]
\draw (0,0) circle [radius=1cm];
\foreach \a in {0,30,...,330}{
\draw (\a:1cm-1pt) -- (\a:1cm+1pt);
\tikzmath {
int \b;
if \a<90 then { \b = \a; } else {
if \a==90 then { \b = 0; } else {
if \a<270 then { \b = \a+180; } else {
if \a==270 then { \b = 0; } else {
if \a<360 then { \b = \a; };
};
};
};
};
};
\draw (\a:1cm+1pt) node[rotate=\b,anchor=west]  {$\a^\circ$};
}
\end{tikzpicture}
\end{document}


Can this code be extended to set the anchor values of the nodes from a variable set within the conditionals? Something like the following dysfunctional code.

...
\tikzmath {
int \b;
if \a<90 then { \b = \a; \c = west; } else {
if \a==90 then { \b = 0; \c = south; } else {
if \a<270 then { \b = \a+180; \c = east; } else {
if \a==270 then { \b = 0; \c = north; } else {
if \a<360 then { \b = \a; \c = west; };
};
};
};
};
};
\draw (\a:1cm+1pt) node[rotate=\b,anchor=\c]  {$\a^\circ$};
...


Obviously the math library is not intended to handle this.

Sure, I could just split the loop but isn't there something more straight forward?

I'm not sure I understand your question correctly, but here's my take: You can pass an angle to the anchor key to get the anchor at that angle on the border of the node. So you'd just have to calculate the correct angles.

\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{lmodern}

\usepackage{tikz}

\usepackage{siunitx}

\begin{document}

\begin{tikzpicture}[scale=3]
\draw (0,0) circle [radius=1cm];
\foreach \a in {0,30,...,330}{
\draw (\a:1cm-1pt) -- (\a:1cm+1pt);
\pgfmathsetmacro\anchr{
ifthenelse(
mod(\a, 90),
floor((floor(mod(floor(\a/90), 4)) - 1) / 2) * 180,
(2 + floor(mod(floor(\a/90), 4))) * 90
)
}
\pgfmathsetmacro\rottn{
ifthenelse(
mod(\a, 90),
\a + \anchr + 180,
0
)
}
\path (\a:1cm) node [anchor=\anchr, rotate=\rottn, outer sep=1ex] {\ang{\a}};
}
\end{tikzpicture}

\end{document}


However, I find the following much more pleasing (and easier to do).

\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{lmodern}

\usepackage{tikz}

\usepackage{siunitx}

\begin{document}

\begin{tikzpicture}[scale=3]
\draw (0,0) circle [radius=1cm];
\foreach \a in {0,30,...,330}{
\draw (\a:1cm-1pt) -- (\a:1cm+1pt);
\path (\a:1cm) node [anchor=\a+180, outer sep=1ex] {\ang{\a}};
}
\end{tikzpicture}

\end{document}


• Thanks for your instant reply. I really should have a closer look at macros! You are right, your second solution is more pleasing but not an option for me, because I'm going to have somewhat longer text in the nodes and it would interfere with other stuff in the drawing. Cheers! – user234416 Feb 3 at 13:24