The code adds some completely useless invisible (or rather white) stuff. The lines
\clip(0pt,403pt) -- (389.957pt,403pt) -- (389.957pt,99.6166pt) -- (0pt,99.6166pt) -- (0pt,403pt);
\color[rgb]{1,1,1}
\fill(3.76406pt,399.236pt) -- (380.923pt,399.236pt) -- (380.923pt,253.19pt) -- (3.76406pt,253.19pt) -- (3.76406pt,399.236pt);
\fill(53.4497pt,394.719pt) -- (374.901pt,394.719pt) -- (374.901pt,289.325pt) -- (53.4497pt,289.325pt) -- (53.4497pt,394.719pt);
draw a white background that is larger than the actual picture. TikZ sees that and thinks it is part of the picture. Simply removing/uncommenting these lines removes most of the whitespace.
Near the end of the first scope,
\color[rgb]{1,1,1}
\fill(3.76406pt,249.426pt) -- (386.193pt,249.426pt) -- (386.193pt,103.381pt) -- (3.76406pt,103.381pt) -- (3.76406pt,249.426pt);
does the same.
Additionally (near the end of the second scope
),
\pgftext[center, base, at={\pgfpoint{220.95pt}{106.392pt}}]{\sffamily\fontsize{9}{0}\selectfont{\textbf{ }}}
adds a blank node below the picture, again enlarging the bounding box.
Removing all those lines gives a tight bounding box.
As far as I know, TikZ cannot do the cropping for you, as it can't know whether the white stuff is intentional or not (there might for example be a dark background behind the image so that white is visible).
The problem is what you said, nodes contain letters with different height and depth and they adjust and align according to it. TiKZ manual explains it in tutorial "Diagrams as simple graphs" and "Cell Pictures".
If you want all nodes aligned but without aligning words you can change nodes anchor with anchor=south
.
\documentclass[tikz,border=2mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix[
matrix of nodes,
column sep=1ex, row sep=1ex,
nodes={
draw,
minimum height=2em,
text width=30mm,
anchor=south
},
] (matrix-optimization) {
Encodings &
Problems &
Algorithms \\
%
Selection &
uiae &
pppp \\
};
\end{tikzpicture}
\end{document}
But if you want nodes and text aligned you need to fix a certain depth and height to nodes.
\documentclass[tikz,border=2mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix[text height=1.5ex,text depth=.25ex,
matrix of nodes,
column sep=1ex, row sep=1ex,
nodes={
draw,
minimum height=2em,
text width=30mm
},
] (matrix-optimization) {
Encodings &
Problems &
Algorithms \\
%
Selection &
uiae &
pppp \\
};
\end{tikzpicture}
\end{document}
After posting my answer I've found this previous question which suggest some other solutions: Problem with TikZ and vertical alignment of text inside nodes
Best Answer
The
minimum height
ist the total height, not taking into account theinner sep
of the nodes. Setting theouter sep
to zero will align them nicely:Code
Output