Número ausente, tratado como erro zero ao usar loops for e condicionais no tikz

Número ausente, tratado como erro zero ao usar loops for e condicionais no tikz

Seria bom poder ter um código que, ao modificar certos parâmetros como altura e largura e células para serem coloridas em vermelho ou verde, gerasse uma tabela para mim. O código que tenho já é uma modificação de algo que encontrei, mas não consigo fazer as células coloridas funcionarem. O erro é "Número ausente, tratado como zero". Estou apenas começando no tikz e não entendo muito.

\begin{figure}[H]
\centering
 \begin{tikzpicture}
[
    square/.style = {
        draw, 
        rectangle, 
        minimum size=\m, 
        outer sep=0, 
        inner sep=0, 
        font=\normalsize\bfseries,
        label={[anchor=north,yshift=1.1em,opacity=0.7]south:\scriptsize\label}
    },
]
\def\m{35pt}
\def\w{4}
\def\h{4}

% Array of personalized messages
\def\content{{
    {1, 0, 1, 1},
    {1, 1, 0, 0},
    {0, 0, 1, 0},
    {0, 1, 1, 1}
}}

% Separate arrays for x and y coordinates in greenCoords
\def\greenXCoords{{1, 1, 1, 1}} % x-coordinates
\def\greenYCoords{{1, 2, 3, 4}} % y-coordinates

% Y
\foreach \x in {1,...,\w}
    \foreach \y in {1,...,\h}
    {   
        % Check if the current coordinates match any green cells
        \foreach \i in {1,...,4}
        {
            \ifthenelse{\x=\greenXCoords[\i] \AND \y=\greenYCoords[\i]}
                {\def\fillColor{green!30}\break}
                {\def\fillColor{black!5}}
        }
        
        \pgfmathtruncatemacro{\label}{(\y-1) * \w + \x}
        \node [square, fill=\fillColor]  (Y\x,\y) at (\x*\m,-\y*\m) {\pgfmathparse{\content[\y-1][\x-1]}\pgfmathresult};
    }
\end{tikzpicture}
    \caption{Caption}
    \label{fig:enter-label}
\end{figure}

Tabela obtida

Responder1

A sintaxe da matriz \greenXCoords[\i]é umaSintaxe PGFMathe não compreendido por \ifthenelse.

Você precisará avaliá-los de antemão, digamos

\pgfmathsetmacro\xTest{\greenXCoords[\i]}
\pgfmathsetmacro\yTest{\greenYCoords[\i]}
\ifthenelse{\x=\xTest \AND \y=\yTest}

ou use o próprio PGFMathifthenelsefunçãoou use uma abordagem totalmente diferente para matrizes e condicionais.

Ou você constrói sua tabela sem precisar percorrer tantos arrays e loops. (Uma matriz PGFMath não é a melhor estrutura de dados.)


Aqui está uma solução que percorre o contentvalor diretamente usando sua própria estrutura (já é composta de linhas e colunas).

Alguns estilos e chaves e você poderá construir uma tabela com qualquer conteúdo, qualquer tamanho e qualquer combinação de células verdes.

Aqui, o número de colunas (para o cálculo do rótulo) precisa ser fornecido, mas pode haver soluções que determinem isso automaticamente (a partir da primeira/linha mais longa?) ou apenas contem para cada elemento que não criaria buracos se as linhas não têm o mesmo número de colunas.

Código

\documentclass[tikz]{standalone}
\tikzset{
  % let's do this in our own namespace
  my table/.cd,
  % initial values and settings
  content/.initial={{1, 0, 1, 1},
                    {1, 1, 0, 0},
                    {0, 0, 1, 0},
                    {0, 1, 1, 1}},
  size/.initial=35pt,
  columns/.initial=4,
  square/.style={
    shape=rectangle, draw, minimum size=\pgfkeysvalueof{/tikz/my table/size},
    outer sep=+0pt, inner sep=+0pt, fill=black!5, font=\normalsize\bfseries},
  label/.style={
    label={[anchor=south, font=\scriptsize, lightgray]south:{#1}}},
  % styles to set which rows, cols and cells should be green!30
  green rows/.style={green row/.list={#1}},
  green cols/.style={green col/.list={#1}},
  green cells/.style={green cell/.list={#1}},
  green row/.style={/tikz/my table/rowstyle #1/.append style={fill=green!30}},
  green col/.style={/tikz/my table/colstyle #1/.append style={fill=green!30}},
  green cell/.style={/tikz/my table/style #1/.append style={fill=green!30}}}

% the macro with one optional (!) argument
\newcommand*\PrintTable[1][]{%
  \tikz[
    my table/.cd,#1,content/.get=\myTableContent,
    % make the xyz coordinate system dependent on the size of your squares
    /tikz/x=\pgfkeysvalueof{/tikz/my table/size},
    /tikz/y=\pgfkeysvalueof{/tikz/my table/size}]
  \foreach[count=\myTableY from 0,
           count=\myTableYY from 1]\myTableRow in \myTableContent
    \foreach[count=\myTableX]\myTableCol in \myTableRow
      \node[
        my table/square,
        my table/label=\inteval{\myTableY*
          \pgfkeysvalueof{/tikz/my table/columns}+\myTableX},
        my table/rowstyle \myTableYY/.try,        % 1. row style
        my table/colstyle \myTableX/.try,         % 2. col style
        my table/style \myTableYY-\myTableX/.try, % 3. cell style
      ] at (\myTableX,-\myTableY) {\myTableCol};%
}
\begin{document}
\PrintTable[green cells={1-1, 1-2, 1-3, 1-4}]
\PrintTable[green row=1, columns=3, content={{  1,   2,   3},
                                             { 19,  20,  21},
                                             {123, 456, 789}}]
\end{document}

Saída

insira a descrição da imagem aqui insira a descrição da imagem aqui

informação relacionada