# Adding a number to each cell in a MatrixPlot

I have:

A = RandomInteger[1, {5, 5}];
MatrixPlot[A, Mesh -> All, MeshStyle -> Black, Frame -> None]


Which produces:

Now, I'd like to add the numbers 1 through 25 to the center of each cell. Across the first row: 1,2,3,4,5. Second row: 6,7,8,9,10. Third row: 11,12,13,14,15. Fourth row: 16,17,18,19,20. Fifth row: 21,22,23,24,25.

Does anyone have a nice suggestion as to how I can do this?

A second question. My matrix is filled with 0's and 1's. How can I assign the color yellow to 0 and the color blue to 1?

Thanks for the help.

There's a simple function ColorRules for that. In this specific instance, the text most easily gotten with a Table[] of Graphics[Text[]].

A = RandomInteger[1, {5, 5}];
MatrixPlot[A, Mesh -> All, MeshStyle -> Black, Frame -> None,
ColorRules -> {0 -> Yellow, 1 -> Blue},
Epilog -> {Table[
Text[i + 5 (j - 1), {i - 0.5, 5.5 - j}], {i, 5}, {j, 5}]}]


• Might be better to use Epilog -> Table[Text[...],...] for the labels instead of Show. – MikeLimaOscar Nov 11 '16 at 17:35
• @MikeLimaOscar Arguably yes. – Feyre Nov 11 '16 at 17:37
• @Feyre Thanks for the wonderful help. – David Nov 12 '16 at 4:39

Using ColorFunction and MapIndexed (building on this answer):

A = RandomInteger[1, {5, 5}];

MatrixPlot[A, Mesh -> All, MeshStyle -> Black, Frame -> None,
ColorFunction -> (If[# == 1, Blue, Yellow] &),
Epilog -> {Black,
MapIndexed[Text[#1, #2 - 1/2]&,
Transpose@Reverse@Partition[Range@25, 5], {2}]}]


In MapIndexed, the function Text[#1, #2 - 1/2]& makes automatic placements of the text; I wanted to use simply Range@25 hence the Transpose@Reverse.

• This was also wonderful help and I spent a lot of time trying to figure out the MapIndexed[Text[#1, #2 - 1/2]&, Transpose@Reverse@Partition[Range@25, 5], {2}] command, but I did learn a lot. Thanks. – David Nov 12 '16 at 4:40