1
$\begingroup$

I have:

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

Which produces:

enter image description here

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.

$\endgroup$
4
$\begingroup$

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}]}]

enter image description here

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

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}]}]

enter image description here

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.

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – David Nov 12 '16 at 4: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.