我正在尝试使用 制作一个表格tabularx
,其中单元格会根据其值自动着色。
我想使用该\cellcolor
命令,因为它将填充整个单元格,而不是colorbox
似乎仅填充数字周围区域的命令,并且必须摆弄\fboxsep
才能获得合适的填充。
这是一个 MWE,其中的Value 1
列手动着色,该Value 2
列应该看起来相同,但是在将数值传递给时出现错误\cellcolor
,这表明我有一个Undefined Control Sequence
\documentclass[11pt]{book}% openany
\usepackage{color}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\usepackage{mathtools}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\usepackage{tabularx}
\usepackage{collcell}
\colorlet{LightSpringGreen}{white!70!lime}
\colorlet{LightRed}{white!70!red}
\newcommand{\MinNumber}{0}%
\newcommand{\MaxNumber}{0}%
\newcommand{\ApplyGradient}[1]{%
\pgfmathsetmacro{\PercentColor}{100.0*(#1-\MinNumber)/(\MaxNumber-\MinNumber)}
\cellcolor{LightSpringGreen!\PercentColor!LightRed}{#1}
}
\newcolumntype{H}{>{\collectcell\ApplyGradient}X<{\endcollectcell}}
\begin{document}
\begin{table}
\renewcommand{\MinNumber}{0}%
\renewcommand{\MaxNumber}{1}%
\begin{tabularx}{\textwidth}{l|l|H}
\hline
Name & Value 1 & \multicolumn{1}{c}{Value 2} \\
\hline
a & \cellcolor{LightSpringGreen!20!LightRed}0.2 & 0.2\\
b & \cellcolor{LightSpringGreen!50!LightRed}0.5 & 0.5\\
c & \cellcolor{LightSpringGreen!60!LightRed}0.6 & 0.6\\
d & \cellcolor{LightSpringGreen!80!LightRed}0.8 & 0.8\\
\end{tabularx}
\end{table}
\end{document}
问题似乎与数字传递方式有关。在测试运行中,如果我输入\num{20}
第 2 列、第 2 行,则会出现相同的错误。
谁能告诉我我哪里错了?
答案1
\PercentColor
每个表格单元格组成一个组,因此当达到时,您的定义就会丢失\ApplyGradient
。如果您进行定义\global
(我已经使用\global\edef
或等效地进行\xdef
定义),它会按预期工作:
\documentclass{article}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\usepackage{pgfplots}
\pgfplotsset{compat=1.10}
\usepackage{tabularx}
\usepackage{collcell}
\colorlet{LightSpringGreen}{white!70!lime}
\colorlet{LightRed}{white!70!red}
\newcommand{\MinNumber}{0}%
\newcommand{\MaxNumber}{0}%
\newcommand{\ApplyGradient}[1]{%
\pgfmathsetmacro{\PercentColor}{100.0*(#1-\MinNumber)/(\MaxNumber-\MinNumber)}
\xdef\PercentColor{\PercentColor}%
\cellcolor{LightSpringGreen!\PercentColor!LightRed}{#1}
}
\newcolumntype{H}{>{\collectcell\ApplyGradient}X<{\endcollectcell}}
\begin{document}
\begin{table}
\renewcommand{\MinNumber}{0}%
\renewcommand{\MaxNumber}{1}%
\begin{tabularx}{\textwidth}{l|l|H}
\hline
Name & Value 1 & \multicolumn{1}{c}{Value 2} \\
\hline
a & \cellcolor{LightSpringGreen!20!LightRed}0.2 & 0.2\\
b & \cellcolor{LightSpringGreen!50!LightRed}0.5 & 0.5\\
c & \cellcolor{LightSpringGreen!60!LightRed}0.6 & 0.6\\
d & \cellcolor{LightSpringGreen!80!LightRed}0.8 & 0.8\\
\end{tabularx}
\end{table}
\end{document}