如何用不同的颜色填充表格单元格?我尝试了 diagbox 包,但如您所见,它不起作用。我对对角线不太感兴趣。我只想将单元格分成两个三角形,在两个三角形中放置文本并用不同的颜色填充它们。
\documentclass{article}
\usepackage{tabularx}
\usepackage{colortbl}
\usepackage{diagbox}
\begin{document}
\begin{tabularx}{8cm}{|X|X|X|X|}
\hline
\diagbox{\cellcolor{red}Time}{\cellcolor{green}Day} & Mon & Tue & Wed\\
\hline
Morning & used & used &\\
\hline
Afternoon & & used & used\\
\hline
\end{tabularx}
\end{document}
答案1
拥有强大的tikz
和tikzmark
:
\documentclass{article}
\usepackage{tabularx}
\usepackage{colortbl}
\usepackage{tikz}
\newcommand\tikzmark[2][]{
\tikz[remember picture,inner sep=\tabcolsep,outer sep=0,baseline=(#1.base),align=left]{\node[minimum width=\hsize](#1){$#2$};}
}
\begin{document}
\begin{tabularx}{8cm}{|X|X|X|X|}
\hline
\multicolumn{1}{|@{}X@{}|}{\tikzmark[a]{\raisebox{-1ex}{Time}\raisebox{1ex}{\hspace{1ex}Day}}} & Mon & Tue & Wed\\
\hline
Morning & used & used &\\
\hline
Afternoon & & used & used\\
\hline
\end{tabularx}
\begin{tikzpicture}[remember picture,overlay]
\path[fill=red,opacity=0.2](a.north west)--(a.south west) -- (a.south east) -- cycle;
\path[fill=green,opacity=0.2](a.north east)--(a.south east) -- (a.north west) -- cycle;
\end{tikzpicture}
\end{document}
使用overlay
,很难设置背景。您可以重新绘制节点(虽然看起来很丑)
\documentclass{article}
\usepackage{tabularx}
\usepackage{colortbl}
\usepackage{tikz}
\newcommand\tikzmark[2][]{
\tikz[remember picture,inner sep=\tabcolsep,outer sep=0pt,baseline=(#1.base),align=left]{\node[minimum width=\hsize](#1){$#2$};}
}
\usetikzlibrary{positioning}
\begin{document}
\begin{tabularx}{8cm}{|X|X|X|X|}
\hline
\multicolumn{1}{|@{}X@{}|}{\tikzmark[a]{\raisebox{-2.5ex}{Time}\raisebox{1ex}{\hspace{0.9ex}Day}}} & text text text text & Tue & Wed\\
\hline
Morning & used & used &\\
\hline
Afternoon & & used & used\\
\hline
\end{tabularx}
\begin{tikzpicture}[remember picture,overlay]
\path[fill=red,opacity=1](a.north west)--(a.south west) -- node [pos=.5, above left=0.5ex and -0.75ex] {Time}(a.south east) -- cycle ;
\path[fill=green,opacity=1](a.north west)-- node [pos=.5, below right=0.5ex and 0.1ex] {Day}(a.north east)-- (a.south east) -- cycle;
\end{tikzpicture}
\end{document}
适当调整ex
数值。
答案2
{NiceTabularX}
这是使用的解决方案nicematrix
。该环境类似于经典环境{tabularx}
(同名包),但在单元格、行和列下创建 PGF/Tikz 节点。可以将这些节点与 Tikz 一起使用,在表格中绘制或填充您想要的任何内容。
\documentclass{article}
\usepackage{nicematrix,tikz}
\begin{document}
\renewcommand{\arraystretch}{1.4}
\begin{NiceTabularX}{8cm}{XXXX}[hvlines]
\CodeBefore
\begin{tikzpicture}
\fill [red!15] (1-|1) |- (2-|2) -- cycle ;
\fill [green!15] (1-|1) -| (2-|2) -- cycle ;
\end{tikzpicture}
\Body
\diagbox{Time}{Day} & Mon & Tue & Wed \\
Morning & used & used & \\
Afternoon & & used & used \\
\end{NiceTabularX}
\end{document}
您需要多次编译(因为 PGF/Tikz 节点)。