2

I have a Tikz picture that contains a matrix. I would like to center the header text and highlight some specific cells. It is important that it is a matrix and not a tabular.

I have tried the following:

\documentclass[tikz]{standalone}
\usetikzlibrary{arrows,shapes,snakes,automata,backgrounds,petri, fit,positioning,matrix}
\begin{document}
\tikzset{
    state/.style={
           %draw=black,
           nodes={
             %text width=width(":pi2"),
             align=left,
             anchor=west
           },
           inner sep=2pt,
            matrix of nodes,
           },
           row 1/.style = {nodes={anchor=base }}
}
\tikzset{highlight/.style args = {(#1,#2)}{row #1 column #2/.style={fill=red!50,minimum width=1cm}}}

\begin{tikzpicture}[]

 \matrix[state,highlight/.list={(2,4),(3,4),(4,4)}] (IT) 
 {%
    S & P & O & C \\ \hline
    :book & :title & ``Dracula'' & :pi1  \\
    :book & :author & :stoker & :pi1  \\
    :stoker & :name & ``Bram Stoker'' & :pi2  \\
 };

\end{tikzpicture}
\end{document}

enter image description here

The first problem is that the headline in the matrix is not centered? The other cells are set to anchor=west and the header is anchor=base, however, this does not do as expected.

I have found a Tikz guide that showed how to make a Tikz style that receives arguments, but I do not work when combined with my other style. How can I both style my matrix and highlight some cells? It is not a bad option to hard code the highlighting because the state style is used by other matrixes that have different highlighting.

Cheers

4

you are missing nodes at some places. Other than that, note that the column width is not necessarily the width of the node inside them. You can add draw option to see this. Hence I've added 1cm minimum width to have some space within the node for center alignment.

\documentclass[tikz]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\tikzset{
    state/.style={
           %draw=black,
           nodes={
             %text width=width(":pi2"),
             align=left,
             anchor=west
           },
           inner sep=2pt,
            matrix of nodes,
           },
           row 1/.style = {nodes={align=center,minimum width=1cm}}
}
\tikzset{highlight/.style args = {(#1,#2)}{row #1 column #2/.style={nodes={fill=red!50,minimum width=1cm}}}}

\begin{tikzpicture}[]

 \matrix[state, highlight/.list={(2,4),(3,4),(4,4)}] (IT) 
 {%
    S & P & O & C \\ \hline
    :book & :title & ``Dracula'' & :pi1  \\
    :book & :author & :stoker & :pi1  \\
    :stoker & :name & ``Bram Stoker'' & :pi2  \\
 };

\end{tikzpicture}
\end{document}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.