4
$\begingroup$

I want to use Grid to tabulate the following list and have the same background color for rows of the same value on column 4. The actual list is very long.

list=
{{1, {2, 1, 1}, {1, 0, -1, 1}, 4.48},
 {2, {-2, -1, -1}, {-1, 0, 1, -1}, 4.48},
 {3, {2, 1, 1}, {1, 0, -1, 1}, 4.48},
 {4, {-2, -1, -1}, {-1, 0, 1, -1}, 4.48},
 {9, {-2, -1, 1}, {-1, 0, 1, 1}, 4.48},
 {10, {2, 1, -1}, {1, 0, -1, -1}, 4.48},
 {11, {2, 1, -1}, {1, 0, -1, -1}, 4.48},
 {12, {-2, -1, 1}, {-1, 0, 1, 1}, 4.48},
 {5, {0, -1, 0}, {1, -2, 1, 0}, 5.266},
 {6, {0, -1, 0}, {1, -2, 1, 0}, 5.266},
 {7, {0, 1, 0}, {-1, 2, -1, 0}, 5.266},
 {8, {0, 1, 0}, {-1, 2, -1, 0}, 5.266},
 {5, {1, -4, 0}, {2, -3, 1, 0}, 5.6323},
 {6, {1, -4, 0}, {2, -3, 1, 0}, 5.6323},
 {7, {-1, 4, 0}, {-2, 3, -1, 0}, 5.6323},
 {8, {-1, 4, 0}, {-2, 3, -1, 0}, 5.6323}}

I found a solution to a similar question here. I wonder how can I build the colorrules elegantly. Thanks.

$\endgroup$
5
$\begingroup$

Here is a solution with Item[...] :

itemRules = 
  With[{color = RandomColor[]},
    (x : {___, #}) :>  (Item[#,Background -> color] & /@ x)] & /@ Union[list[[All, 4]]];

Grid[list /. itemRules, Dividers -> All] 

enter image description here

$\endgroup$
4
$\begingroup$
sets = GatherBy[Transpose[{Range[Length[list]], list[[All, 4]]}], #[[2]] &];
colors = {LightYellow, LightOrange, LightBlue};
colorrules = 
 Flatten@Table[
   Thread[sets[[n, All, 1]] -> colors[[n]]], {n, Length[sets]}];

Grid[list, Frame -> All, Background -> {None, colorrules}]

enter image description here

$\endgroup$
3
$\begingroup$

Using Association and Lookup to specify row backgrounds:

keys = Union @ list[[All, -1]];
colors = Lighter @* Lighter @* ColorData["Rainbow"] /@ Rescale[keys];
backgroundColors = AssociationThread[keys, colors];

Legended[Grid[list,  Frame -> All, 
  Background -> {None, Lookup[list[[All, -1]]] @ backgroundColors}],
 SwatchLegend[colors, keys]]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.