4
$\begingroup$

Is it possible to apply a color function to table cells based on the magnitude of their content? For instance, in the table

TableForm@Table[10^(x + y), {x, 0, 4}, {y, 0, 4}]

I would like the cell background color to change from blue for small numbers in the top left to red for large numbers in the bottom right. (Other than the background, the cell content should remain unaffected.) Is this possible?

$\endgroup$
  • $\begingroup$ Do you need to display the numbers too? If not, ArrayPlot has a ColorFunction option. $\endgroup$ – Alan Jun 7 '17 at 14:18
  • $\begingroup$ @Alan Yes, the numbers too. $\endgroup$ – Casimir Jun 7 '17 at 14:20
7
$\begingroup$
table = Table[10^(x + y), {x, 0, 4}, {y, 0, 4}];

(* You have to manually set the second argument according to the content of the table. *)
rescale = Rescale[Log[10, #], {0, 8}] &;

color = Blend[{Red, Blue}, rescale[#]] &;

TableForm@Map[
  Style[#, color[#]] &,
  table,
  {2}
  ]

table1

Edit 1: I have just realized, that you asked for coloring the background of cells. Just a small change in code is needed.

TableForm@Map[
  Item[#,
    Background -> Directive[Opacity[0.7], color[#]]
    ] &,
  table,
  {2}
  ]

table2

Edit 2: Extension to incorporate wish from OP comment.

table = Table[{x, y, 10^(x + y)}, {x, 0, 4}, {y, 0, 4}];

TableForm@Map[
  Item[#,
    Background -> Directive[Opacity[0.7], color[#[[3]]]]
    ] &,
  table,
  {2}
  ]

table3

$\endgroup$
  • $\begingroup$ @Two more questions: 1. What if the table is Table[{x,y,10^(x + y)}, {x, 0, 4}, {y, 0, 4}]? 2. How can I reduce the opacity of the cell background? $\endgroup$ – Casimir Jun 7 '17 at 14:52
  • $\begingroup$ Nice. One last thing: Is there a way to make this work with TableForm, as used in the OP? $\endgroup$ – Casimir Jun 8 '17 at 9:40

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.