I am trying to draw a "table" in tikz
, and more generally, to work it out so that it is easy to write a lot of them.
The matrix
library makes it a lot easier to place aligned nodes. The next step would be to be able to draw vertical and horizontal lines.
I have tried several approaches (some of them "just to be sure"):
- using nodes anchors as described for example in the answer to this question (does not work if nodes have variable height or width, see the blue and red lines below)
- using nodes for the columns or rows, using the
fit
library as described in answers to this question (better than the previous, see the orange line, but still some problems if the row (resp column) is not as wide (resp high) as the matrix [see the green line].
It is worth noting that horizontal lines can be drawn with \hline
(but it lacks the customizability of tikz paths).
So the question: how to draw this kind of lines in a consistent way?
Edit (more information after the first answer)
I understand that it is possible to force the anchors to be aligned by specifying the height, depth and width of each cell. However, isn't that exactly what pgf
did when drawing the matrix?
So the point of the question would be (if at all possible) to access this information (the position of the intersections of the bounding box of the matrix, and the limits of the areas between rows and columns), as computed by pgf
, after the matrix is drawn.
MWE:
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix,fit}
\begin{document}
\begin{tikzpicture}%[every node/.style={draw=black!30}]
\node[%
matrix of nodes,%
every node/.append style={%
inner xsep=5pt,
inner ysep=5pt,
outer sep=0pt
},
row sep=0pt,
column sep=0pt
] (M) {
{} & 1 & 2 \\
1 & 1 & 2 \\
2 & 2 & 4 \\
3 & 3 & 6 \\
1000000 & 1000000 & 2000000 \\
};
\draw[red] (M-1-2.north west) -- (M-5-1.south east);
\draw[blue] (M-1-1.north east) -- (M-5-1.south east);
\node[fit=(M-1-3) (M-5-3),inner sep=0pt] (C3) {};
\draw[orange!80!black] (C3.north west) -- (C3.south west);
\node[fit=(M-2-1) (M-2-3),inner sep=0pt] (R2) {};
\draw[green!50!black] (R2.north west) -- (R2.north east);
\end{tikzpicture}
\end{document}
Output:
Output with cell borders:
Related questions: