将矩阵结构中的数字转换为彩色方块

将矩阵结构中的数字转换为彩色方块

假设我们有一个数字矩阵

$$\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}

在此处输入图片描述

相关内容