I have used the latex command presented in this TexStackExchange answer to create a table with cell background color based on the cell's numerical value.
The code works but it is changing the cell width. While the newly defined command uses \cellcolor, the same behavior does not occur when using \cellcolor directly.
Here is an example document which illustrates the problem:
\documentclass[table]{article}
\usepackage{hhline} % used for the top-most horizontal line! in order to fix the top left corner cell empty
\usepackage[table]{xcolor}
\usepackage{etoolbox}
\usepackage{pgf} % for calculating the values for gradient
%======================================
% Color set related!
\definecolor{high}{HTML}{0083b6} % the color for the highest number in your data set
\definecolor{low}{HTML}{ffffff} % the color for the lowest number in your data set
\newcommand*{\opacity}{70}% here you can change the opacity of the background color!
%======================================
% Data set related!
\newcommand*{\minval}{0.0}% define the minimum value on your data set
\newcommand*{\maxval}{1.0}% define the maximum value in your data set!
%======================================
% gradient function!
\newcommand{\gradient}[1]{
% The values are calculated linearly between \minval and \maxval
\ifdimcomp{#1pt}{>}{\maxval pt}{#1}{
\ifdimcomp{#1pt}{<}{\minval pt}{#1}{
\pgfmathparse{int(round(100*(#1/(\maxval-\minval))-(\minval*(100/(\maxval-\minval)))))}
\xdef\tempa{\pgfmathresult}
\cellcolor{high!\tempa!low!\opacity} #1
}}
}
\renewcommand{\opacity}{50}
\begin{document}
\begin{table}[ht]
\centering
\caption{Version A}
\label{tab:mytab}
\begin{tabular}{|{8}{c|}}
\hhline{~{3}{-}}
\multicolumn{1}{c|}{} & A & B & C \ \hline
1 & \gradient{0.20} & \gradient{0.00} & \cellcolor{red}{0.00} \ \hline
6 & \gradient{0.80} & \gradient{1.00} & \cellcolor{red}{0.00} \ \hline
\end{tabular}
\end{table}
\begin{table}[ht]
\centering
\caption{Version B}
\label{tab:mytab}
\begin{tabular}{|{8}{c|}}
\hhline{~{3}{-}}
\multicolumn{1}{c|}{} & A & B & C \ \hline
1 & \gradient{0.20} & \gradient{0.00} & \gradient{0.00} \ \hline
6 & \gradient{0.80} & \gradient{1.00} & \gradient{0.00} \ \hline
\end{tabular}
\end{table}
\end{document}
Does anyone know how to keep the same cell width?


\gradient. Make sure to end every line in the defintion with a%and/or remove empty lines from the code of the defintion. – Jasper Habicht May 08 '23 at 13:55\gradientend each line with%to remove them. I added 7 (probably not all needed) to your example and the two tables have the same width (if you also remove the space before#1on the\cellcolorline). – daleif May 09 '23 at 07:50