![将矩阵结构中的数字转换为彩色方块](https://linux22.com/image/376922/%E5%B0%86%E7%9F%A9%E9%98%B5%E7%BB%93%E6%9E%84%E4%B8%AD%E7%9A%84%E6%95%B0%E5%AD%97%E8%BD%AC%E6%8D%A2%E4%B8%BA%E5%BD%A9%E8%89%B2%E6%96%B9%E5%9D%97.png)
假设我们有一个数字矩阵
$$\begin{matrix}
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\ \end{matrix}$$
我想在 MathJAx 中将数字矩阵转换为条目为彩色方块的矩阵。此示例可以是文本以下然而,它有一个缺点,就是它在方块之间插入了垂直和水平的空间。
如何在不增加间距的情况下做到这一点?(获得连续的矩形颜色区域)
$\begin{matrix}
\color{red}\blacksquare \color{olive}\blacksquare \color{teal}\blacksquare \color{blue}\blacksquare \\
\color{red}\blacksquare \color{olive}\blacksquare \color{teal}\blacksquare \color{blue}\blacksquare \\
\color{red}\blacksquare \color{olive}\blacksquare \color{teal}\blacksquare \color{blue}\blacksquare \\ \end{matrix}$
答案1
您可以使用如下方法:
\documentclass[]{article}
\usepackage[table]{xcolor}
\usepackage{collcell}
\newcolumntype{\colored}{>{\collectcell\colored}l<{\endcollectcell}}
\newcommand*\colored[1]
{%
\ifcase#1
\cellcolor{white}% if cell content is evaluated to be the number 0
\or \cellcolor{red}% 1
\or \cellcolor{olive}% 2
\or \cellcolor{teal}% 3
\or \cellcolor{blue}% 4
% add more \or \cellcolor constructs for more colours
\fi
}
\begin{document}
\begin{tabular}[]{*4\colored}
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
\end{tabular}
\end{document}
上图中的白线是渲染问题pdftocairo
。如果使用 放大 800%,则xpdf
没有接缝。
如果您稍微改变(宏而不是列)的定义,\colored
您甚至可以将内容放在表格单元格内(同时仍为它们着色)。如果内容以数字开头,则该数字被视为颜色规范,其余部分是排版。
\documentclass[]{standalone}
\usepackage[table]{xcolor}
\usepackage{collcell}
\newcolumntype{\colored}{>{\collectcell\colored}l<{\endcollectcell}}
\newcommand*\colored[1]
{%
\ifcase0#1
\cellcolor{white}% if cell content is evaluated to be the number 0
\or \cellcolor{red}\ifnum0<#1\fi% 1
\or \cellcolor{olive}\ifnum0<#1\fi% 2
\or \cellcolor{teal}\ifnum0<#1\fi% 3
\or \cellcolor{blue}\ifnum0<#1\fi% 4
% add more \or \cellcolor constructs for more colours
% if the encountered number is greater than the defined ones \else is
% used
\else \cellcolor{white}\ifnum0<#1\fi
\fi
}
\begin{document}
\begin{tabular}[]{*4\colored}
0 different & content & is & possible\\
1 foo & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
\end{tabular}
\end{document}