Message Boards Message Boards

0
|
1916 Views
|
5 Replies
|
5 Total Likes
View groups...
Share
Share this post:

How can I add background colour programmatically to certain cells of a grid

Posted 8 months ago

Hi everyone,

I have a matrix of numbers that I want to display as a grid and have the cells containing numbers > 135 highlighted. My approach was to pre-compute the position of the cells to be highlighted, and I'm wondering if there is a slicker way to do it. This is what I did.

(the data)

d = {
{129, 62, 60, 123, 62, 58, 144, 75, 56, 145, 79, 57},
{124, 67, 57, 126, 72, 59, 138, 71, 59, 137, 74, 56},
{132, 69, 62, 119, 67, 61, 125, 66, 62, 122, 67, 65},
{133, 75, 60, 130, 71, 62, 136, 66, 67, 136, 67, 67},
{128, 66, 53, 116, 69, 53, 139, 66, 52, 135, 67, 53},
{121, 64, 57, 118, 67, 58, 134, 71, 54, 136, 72, 56},
{128, 70, 54, 123, 61, 51, 139, 72, 58, 134, 69, 54},
{114, 62, 56, 116, 59, 54, 126, 65, 52, 119, 64, 53},
{125, 65, 57, 122, 65, 54, 130, 63, 63, 131, 62, 61},
{124, 67, 59, 125, 67, 59, 122, 62, 54, 128, 64, 55}
};

(*position of cells with values > 135*)
highlightPos = Position[d, _?(# > 135 &)];

(*the grid*)
Grid[
d,
Background -> {None, None, Map[# -> LightGray &, highlightPos]},
Alignment -> Automatic
]
POSTED BY: Gregory Lypny
5 Replies
Posted 8 months ago

Thanks for answering it, you made my day. If I want to know more, I will message you.

POSTED BY: Verona Ortiz
Posted 8 months ago

Hi Gianluca,

Thanks for the tip. Sorry for not reply sooner. For some reason I did not receive an email notification.

Greg

POSTED BY: Gregory Lypny
Posted 8 months ago

To highlight the cell use Item

Grid[d /. n_Integer /; n > 135 :> Item[n, Background -> LightGray]]

To see the difference with Gianluca's answer more clearly

Grid[d /. n_Integer /; n > 135 :> Style[n, Background -> LightGray], Frame -> All]

enter image description here

Grid[Map[If[# > 135, Item[#, Background -> LightGray], #] &, d, {2}], Frame -> All]

enter image description here

POSTED BY: Rohit Namjoshi
Posted 8 months ago

Hi Rohit,

Crystal clear. Good stuff, thanks!

Greg

POSTED BY: Gregory Lypny

This highlights the numbers, not the cells, but it is simple:

Grid[d /. n_Integer /; n > 135 :> Style[n, Background -> LightGray]]
POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract