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$
2
  • $\begingroup$ Do you need to display the numbers too? If not, ArrayPlot has a ColorFunction option. $\endgroup$
    – Alan
    Jun 7, 2017 at 14:18
  • $\begingroup$ @Alan Yes, the numbers too. $\endgroup$
    – Janosh
    Jun 7, 2017 at 14:20

1 Answer 1

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$
2
  • $\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$
    – Janosh
    Jun 7, 2017 at 14:52
  • $\begingroup$ Nice. One last thing: Is there a way to make this work with TableForm, as used in the OP? $\endgroup$
    – Janosh
    Jun 8, 2017 at 9:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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