TransWikia.com

Split cell into five equally sized "sub-cells" with fixed width

TeX - LaTeX Asked by Andreas Unterweger on May 3, 2021

I am trying to color cells of a table with 3 rows of 2 cm width each using tabularx and cellcolor. I want to split an arbitrary number of cells of this table into “sub-cells” with different colors, but I can’t get the spacing right even with one split-up cell:

documentclass{article}

usepackage{tabularx}
usepackage{xcolor}
usepackage{colortbl}

begin{document}

begin{tabularx}{6cm}{|X|>{hsize=.2hsize}X@{}>{hsize=.2hsize}X@{}>{hsize=.2hsize}X@{}>{hsize=.2hsize}X@{}>{hsize=.2hsize}X|X|}
  cellcolor{gray} &
      cellcolor{red} & cellcolor{green} & cellcolor{yellow} & cellcolor{orange} & cellcolor{blue} &
  cellcolor{gray} 
  1 & multicolumn{5}{X|}{2} & 3
end{tabularx}

end{document}

As can be seen below, the blue “sub-cell” is far bigger than the red, green, yellow and orange ones, which are too small. In total, the width seems to be o.k., though.

Example with incorrect sizes

I found some tikz-based solutions here, but they use overlays which I am trying to avoid because I will likely be using a large number of tables and “sub-cells” for illustrating a document that I am currently working on. Is there any way to split each cell into “sub-cells” of equal width?

2 Answers

For that kind of figure/table I would really consider Tikz:

documentclass{article}
usepackage{tikz}
begin{document}
begin{tikzpicture}
  fill[gray](0,0) rectangle (15,1.5);
  foreach x/col in {5/red,6/green,7/yellow,8/orange,9/blue}{
    fill[col] (x,0) rectangle +(1,1.5);
  }
  foreach x/label in {0/1,5/2,10/3,15/}{
    draw[thin] (x,-1.5) -- +(0,3) node[pos=0.5,anchor=north west]{Hugelabel};
  }
end{tikzpicture}
end{document}

enter image description here

Correct answer by StefanH on May 3, 2021

Here is a way to do that with {NiceTabular} of nicematrix.

That environment is similar to {tabular} (of array) but creates PGF/Tikz nodes under the cells, row and columns.

So, it's possible to add a Tikz picture in a cell by using the nodes created by nicematrix.

documentclass{article}
usepackage{nicematrix,tikz}
usetikzlibrary{calc}

begin{document}

begin{NiceTabular}{lll}[hvlines,colortbl-like]
CodeBefore
  tikz
    foreach x / col in {0/red,1/green,2/yellow,3/orange,4/blue}
      { fill [col] ($(1-|2)!0.2*x!(1-|3)$) rectangle ($(2-|2)!0.2*x+0.2!(2-|3)$) ; } ;
Body
cellcolor{gray}  &   &cellcolor{gray}   
1 & 2 & 3 
4 & bla bla bla  & 6 
end{NiceTabular}

end{document}

You need several compilations (because nicematrix uses PGF/Tikz nodes).

Output of the above code

Answered by F. Pantigny on May 3, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP