Reputation: 11628
In the following example I would expect the vertical lines of the rectangles to be aligned, but for some reason they are not. I assume this is because not the actual coordinates of the nodes are used, but they in include some kind of offset. I also tried using .base
for each of the nodes in the rectangle command, but it didn't solve that problem.
How can I access the actual coordinates I defined in the nodes?
\documentclass[a4paper]{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\node (d) at (0, 7) [anchor=west] {$D_i$};
\node (c) at (0, 5) [anchor=west] {$C^j$};
\node (b) at (0, 3) [anchor=west] {$B_k$};
\node (a) at (0, 1) [anchor=west] {$A$};
\draw ($(a)+(-1, -1)$) rectangle ($(b)+(1,1)$);
\draw ($(c)+(-1, -1)$) rectangle ($(d)+(1,1)$);
\end{tikzpicture}
\end{document}
Update: I realize the alignment problem can be solved by defining the cooridnates first like in the following code, but I'd be still interested to hear how to extract the actual coordinates from a node.
\documentclass[a4paper]{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}
\coordinate (d) at (0, 7);
\coordinate (c) at (0, 5);
\coordinate (b) at (0, 3);
\coordinate (a) at (0, 1);
\node at (d) [anchor=west] {$D_i$};
\node at (c) [anchor=west] {$C^j$};
\node at (b) [anchor=west] {$B_k$};
\node at (a) [anchor=west] {$A$};
\draw ($(a)+(-1, -1)$) rectangle ($(b)+(1,1)$);
\draw ($(c)+(-1, -1)$) rectangle ($(d)+(1,1)$);
\end{tikzpicture}
\end{document}
Upvotes: 1
Views: 1291
Reputation: 38967
instead of manually calculating the corners of the rectangle with ($(a)+(-1, -1)$)
etc, you could use the corners of nodes with (a.south west)
etc.
to avoid misalignment, make sure all your nodes have the same size by specifying a big enough minimum width and height
it might be more convenient to position the nodes below each other with the positioning
library
\documentclass[a4paper]{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}[every node/.style={minimum width=2cm,minimum height=2cm}]
\node (d) at (0, 7) {$D_i$};
\node[below of=d] (c) {$C^j$};
\node[below of=c,anchor=north] (b) {$B_k$};
\node[below of=b] (a) {$A$};
\draw (a.south west) rectangle (b.north east);
\draw (c.south west) rectangle (d.north east);
\end{tikzpicture}
\end{document}
Upvotes: 1