[Tex/LaTex] Draw a box around matrix elements

matrices

I studied the examples in Highlight elements in the matrix and developed my example:

enter image description here

The code is the following:

 \documentclass{article}
 \usepackage{tikz}
 \usetikzlibrary{matrix}
 \begin{document}

 \begin{tikzpicture}
   \matrix (m)[matrix of math nodes,nodes in empty cells, ]
           {
         0    & -26  & 111 & 5  & -1     & 2    \\
         2666 & 67   & 55  & 77 & 6      & -1   \\
         -1   & 3    & 3   & 3  & 3      & 8    \\
         1    & 2    & 5   & 77 & 7      & 1    \\
         1    & 33   & 44  & 66 & 998888 & -266 \\
         -2   & 1    & 7   & -1 & 2      & 80   \\
       } ;
       \draw (m-1-1.north west) -- (m-2-1.south west) -- (m-2-2.south east) -- (m-1-2.north east) -- cycle;

     \end{tikzpicture}

 \end{document}

What I do not like is that the box is skew.

Another feature that I do not like is that the column widths are not equal – the width of the column containing 998888 is larger.

Is it possible to control these aspects?

I would like to stick to tikz because it has an attractive feature – being able to draw a dotted line across multiple columns/rows (not addressed in the above example).

Best Answer

The rectangle of the example can be easily drawn by specifying opposite corners:

\draw (m-2-1.south west) rectangle (m-1-2.north east);

The general case is covered by Ignasi's answer.

The nodes can be set with a minimum width of the largest entry:

minimum width=width("998888")

Full example:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
  \matrix (m)[
    matrix of math nodes,
    nodes in empty cells,
    minimum width=width("998888"),
  ] {
    0    & -26  & 111 & 5  & -1     & 2    \\
    2666 & 67   & 55  & 77 & 6      & -1   \\
    -1   & 3    & 3   & 3  & 3      & 8    \\
    1    & 2    & 5   & 77 & 7      & 1    \\
    1    & 33   & 44  & 66 & 998888 & -266 \\
    -2   & 1    & 7   & -1 & 2      & 80   \\
  } ;

  \draw (m-2-1.south west) rectangle (m-1-2.north east);

\end{tikzpicture}
\end{document}

Result

Related Question