1

I have many overlapping paths in a drawing and they end up passing over labels (I am not opposed to paths passing over paths). How can I put the label in the foreground, but keep it positioned on the path and sloped? Is there a way to do it with layers or the backgrounds library?

For instance:

\node at (0,0) (1) {x};
\node at (2,2) (2) {y};
\node at (0,2) (3) {m};
\node at (2,0) (4) {n};

\begin{scope}[on background layer] \draw[->] (1) -- node[midway, sloped, fill=white] {-} (2); \draw[->] (3) -- node[near start, sloped, fill=white] {+} (4); \end{scope}

Here, I would want the node[midway, sloped, fill=white] {-} to go into the foreground so it isn't covered by the next path.

Can this be accomplished in a way that every node is affected by some simple operation ideally? Something like usetikzlibrary{all paths in background}?

Sven Voigt
  • 43
  • 4
  • 1
    See: https://tex.stackexchange.com/a/20426/47927 which offers you a key node on layer to put a node sitting on a path onto a certain layer. You could even add every node/.append style={node on layer={front}} as option to the scope (having defined a foreground layer using \usetikzlibrary{backgrounds} \pgfdeclarelayer{front} \pgfsetlayers{main,front}). – Jasper Habicht Jul 13 '23 at 20:22
  • 1
    Unrelated: I'd use $+$ and $-$ to get proper and equally sized plus and minus signs. – Jasper Habicht Jul 13 '23 at 20:33

1 Answers1

1

Using the code from this great answer, you can go the other way around and put the nodes onto a foreground layer. Then, you can use every node in the option list of the scope to apply this key to every node inside the scope:

\documentclass[border=10pt]{standalone}
\usepackage{tikz}
\usetikzlibrary{backgrounds} 
\pgfdeclarelayer{front} 
\pgfsetlayers{main, front}

\makeatletter \pgfkeys{% /tikz/node on layer/.code={ \gdef\node@@on@layer{% \setbox\tikz@tempbox=% \hbox\bgroup\pgfonlayer{#1}\unhbox% \tikz@tempbox\endpgfonlayer\egroup% }% \aftergroup\node@on@layer } } \def\node@on@layer{\aftergroup\node@@on@layer} \makeatother

\begin{document} \begin{tikzpicture} \node at (0,0) (1) {x}; \node at (2,2) (2) {y}; \node at (0,2) (3) {m}; \node at (2,0) (4) {n};

\begin{scope}[every node/.append style={node on layer={front}}] \draw[->] (1) to node[midway, sloped, fill=white] {$-$} (2); \draw[->] (3) to node[near start, sloped, fill=white] {$+$} (4); \end{scope} \end{tikzpicture} \end{document}

But I have to admit that I don't fully understand the code, so credit should go to Andrew Stacey!

enter image description here