我知道如何用一种颜色给表格的一个单元格着色,如下所示:仅为表格的一个单元格着色。但是我想要的是在一个单元格中有多种颜色。
这是我希望实现的模型(抱歉,它太大了,我不知道如何使它变小):
第二个问题是,如果我能够以编程方式调节单元格内容的颜色,那就太好了。所以在我上面的例子中,表格中的所有“a”的背景都是黄色,所有“b”的背景都是棕色,等等。我见过这种情况:表格:基于内容的单元格颜色/条件单元格着色但我认为如果一个单元格中有多种颜色,实现方式会有所不同。
答案1
感谢@GuilhermeZanotelli 提供的解决方案—— https://tex.stackexchange.com/a/349140/197451
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{tikzmark, calc}
% Makes a style for double color filling
\tikzset{
double color fill/.code 2 args={
\pgfdeclareverticalshading[%
tikz@axis@top,tikz@axis@middle,tikz@axis@bottom%
]{diagonalfill}{100bp}{%
color(0bp)=(tikz@axis@bottom);
color(50bp)=(tikz@axis@bottom);
color(50bp)=(tikz@axis@middle);
color(50bp)=(tikz@axis@top);
color(100bp)=(tikz@axis@top)
}
\tikzset{shade, left color=#1, right color=#2, shading=diagonalfill}
}
}
% Code adapted from Gonzalo: https://tex.stackexchange.com/a/67096/81905
\newcommand\BGcell[4][0pt]{%
\begin{tikzpicture}[overlay,remember picture]%
\path[#4] ( $ (pic cs:#2) + (-.5\tabcolsep,1.9ex) $ ) rectangle ( $ (pic cs:#3) + (\tabcolsep,-#1*\baselineskip-.8ex) $ );
\end{tikzpicture}%
}%
\newcounter{BGnum}
\setcounter{BGnum}{1}
\newcommand\cellBG[3]{
\multicolumn{1}{
!{\BGcell{startBG\arabic{BGnum}}{endBG\arabic{BGnum}}{%
#1}
\tikzmark{startBG\arabic{BGnum}}}
#2
!{\tikzmark{endBG\arabic{BGnum}}}}
{#3}
\addtocounter{BGnum}{1}
}
% end of code from Gonzalo
\usepackage{dcolumn, array, booktabs}
\newcolumntype{.}{D{.}{.}{-1}}
\newcommand*{\tabhead}[1]{\multicolumn{1}{c}{#1}}
\begin{document}
\tikzset{%
diagonal fill/.style 2 args={%
double color fill={#1}{#2},
shading angle=45,
opacity=0.8},
other filling/.style={%
shade,
shading=myshade,
shading angle=0,
opacity=0.5}
}
% Other crazy filling options using shading
\pgfdeclarehorizontalshading{myshade}{100bp}{%
color(0bp)=(blue);
color(25bp)=(blue);
color(37.5bp)=(blue);
color(37.5bp)=(brown);
color(50bp)=(brown);
color(50bp)=(green);
color(62.5bp)=(green);
color(62.5bp)=(purple);
color(75bp)=(red);
color(100bp)=(red)}
\begin{tabular}{c.}
\toprule
\cellBG{double color fill={red}{blue}, shading angle=-45, opacity=0.5}{c}{Header 1} & \tabhead{Header 2}\\
\midrule
\cellBG{diagonal fill={yellow}{green}}{c}{Text} & \cellBG{other filling}{.}{1.2333}\\
\cellBG{other filling}{c}{Text} & 154.622\\
Text & 1.244\\
Text & 11.3\\
Text & 121.2\\
\bottomrule
\end{tabular}
\end{document}