内容に基づいてテーブルセルの色をプログラミングする

内容に基づいてテーブルセルの色をプログラミングする

この表は以前のものに基づいて作成したものです質疑応答:

ここに画像の説明を入力してください

ご覧のとおり、ヘッダーに問題があります。
ヘッダーのみの強調表示を無効にするにはどうすればよいでしょうか?

コードは次のとおりです:

\documentclass{article}
\usepackage{booktabs}
\usepackage{colortbl}
\usepackage{xcolor}

\makeatletter
\newcommand*{\yncellcolor}{}
\def\yncellcolor\ignorespaces{\@ifnextchar{1}{\cellcolor{green!20}}{\@ifnextchar{0}{\cellcolor{red!20}}{}}}
\newcolumntype{C}{>{\yncellcolor}c}
\makeatother

\begin{document}
\begin{table}[htp]
\caption{XOR}
\begin{center}
\begin{tabular}{CCCCCCCCCCCCCCCCCC}

\toprule
$Bit$       &   1   &   2   &   3   &   4   &   5   &   6   &   7   &   8   \\
\midrule 
$A$         &   0   &   1   &   0   &   1   &   0   &   1   &   0   &   1   \\
$B$         &   1   &   0   &   1   &   0   &   1   &   0   &   1   &   0   \\
$\bigoplus$ &   1   &   1   &   1   &   1   &   1   &   1   &   1   &   1   \\
\bottomrule

\end{tabular}
\end{center}
\label{XOR}
\end{table}

\end{document}

答え1

このような?

ここに画像の説明を入力してください

MWE を修復 (完了) した後、 で定義された列ヘッダーに異なる列タイプを使用することをお勧めします\multicolumn{1}{c}{...}

\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{booktabs}

\makeatletter
\newcommand*{\yncellcolor}{}
\def\yncellcolor\ignorespaces{\@ifnextchar{1}{\cellcolor{green!20}}{\@ifnextchar{0}{\cellcolor{red!20}}{}}}
\newcolumntype{C}{>{\yncellcolor}c}
\makeatother
\newcommand\mc[1]{\multicolumn{1}{c}{#1}} % <--- new

\begin{document}
    \begin{table}[htp]
\caption{XOR}
\centering
\begin{tabular}{l| *{8}{C}}
    \toprule
$Bit$       &\mc{1} &\mc{2} &\mc{3} &\mc{4} &\mc{5} &\mc{6} &\mc{7} &\mc{8} \\ % <--- changed
    \midrule
$A$         &   0   &   1   &   0   &   1   &   0   &   1   &   0   &   1   \\
$B$         &   1   &   0   &   1   &   0   &   1   &   0   &   1   &   0   \\
$\bigoplus$ &   1   &   1   &   1   &   1   &   1   &   1   &   1   &   1   \\
    \bottomrule
\end{tabular}
\label{XOR}
    \end{table}
\end{document}

注意: テーブル内の垂直線の使用と からのルールの使用は、booktabsうまく連携しません。他の行の組み合わせ (たとえば、パッケージ\hlineB{...}からの行) を検討する必要があります。boldline

\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{boldline}

\makeatletter
\newcommand*{\yncellcolor}{}
\def\yncellcolor\ignorespaces{\@ifnextchar{1}{\cellcolor{green!20}}{\@ifnextchar{0}{\cellcolor{red!20}}{}}}
\newcolumntype{C}{>{\yncellcolor}c}
\makeatother
\newcommand\mc[1]{\multicolumn{1}{c}{#1}} % <--- new

\begin{document}
    \begin{table}[htp]
\caption{XOR}
\centering
\begin{tabular}{>{\rule[-1ex]{0pt}{4ex}$}l<{$} | *{8}{C}}
    \hlineB{2}
\mathrm{Bit} &\mc{1} &\mc{2} &\mc{3} &\mc{4} &\mc{5} &\mc{6} &\mc{7} &\mc{8} \\ % <--- changed
    \hlineB{1.5}
A            &   0   &   1   &   0   &   1   &   0   &   1   &   0   &   1   \\
B            &   1   &   0   &   1   &   0   &   1   &   0   &   1   &   0   \\
\bigoplus    &   1   &   1   &   1   &   1   &   1   &   1   &   1   &   1   \\
    \hlineB{2}
\end{tabular}
\label{XOR}
    \end{table}
\end{document}

ここに画像の説明を入力してください

関連情報