10
$\begingroup$

I'm trying to locate minima / maxima in matrices on a heat map. So I have my 2D matrix and did a MatrixPlot,

my matrix plot

and I can find the position of the smallest value.

My question: how do I place a graphical marker at that position? Like a box to outline field (7,6)?

Completely stumped.

$\endgroup$
5
  • 1
    $\begingroup$ Use the Epilog option. $\endgroup$
    – Szabolcs
    Jan 30, 2013 at 18:04
  • 1
    $\begingroup$ Thanks, Szabolcs! Works just as expected! imgur.com/uArxaPM $\endgroup$ Jan 30, 2013 at 18:40
  • 1
    $\begingroup$ Overlay could work too, but may be more difficult to position. Another possibility is to use Show $\endgroup$ Jan 30, 2013 at 18:43
  • $\begingroup$ If you want an unfilled Rectangle, use {EdgeForm[Black], FaceForm[None], Rectangle[...]}. $\endgroup$
    – Szabolcs
    Jan 30, 2013 at 18:44
  • $\begingroup$ Okay, 'Overlay' did work as well, though with more overhead. The unfilled box Szabolcs suggested is actually what I was fiddling with just now: link - thank you, good sirs! $\endgroup$ Jan 31, 2013 at 14:58

2 Answers 2

17
$\begingroup$

To position the highlight rectangle properly, the array position of the highlighted value must be converted into a graphics coordinate. For a data array of $n$ rows, to highlight the value at row $i$ and column $j$ requires the bottom left corner of the rectangle to be placed at graphics coordinate $\{j-1, n-i\}$

Example:

highlight[data_, patt_, directives_] :=
 {FaceForm[None], EdgeForm[directives],
  Rectangle[{#2 - 1, Length[data] - #1}] & @@@ Position[data, patt]}

data = N@Table[x^2 + y^2, {x, -4, 3, 6/11}, {y, -4, 3, 6/11}];

MatrixPlot[data, Epilog -> {
   highlight[data, Min[data], {Thick, Red}],
   highlight[data, x_ /; 5 < x < 6, {Blue, Dashed}]
   }]

enter image description here

$\endgroup$
0
0
$\begingroup$

This is an addition to Simon's excellent answer. For large matrices, MatrixPlot applies some automatic down-sampling which messes up the coordinates.

Small matrix:

m1 = SparseArray[{i_, i_} -> 1, {100, 100}];
mp1 = MatrixPlot@m1;
marker1 = Rectangle[{0, 60}, {40, 100}];
style = Graphics[{FaceForm[None], EdgeForm[Dashed], #}] &;

Show[mp1, style@marker1]

Small matrix

Large matrix:

m2 = SparseArray[{i_, i_} -> 1, {1000, 1000}];
mp2 = MatrixPlot@m2;
marker2 = Rectangle[{0, 600}, {400, 1000}];

Show[mp2, style@marker2]

Large matrix with wrong scale

One can extract the scale from the second argument of the plot's Raster and correct the marker coordinates accordingly:

scaleToRaster[coords_, dims_, plot_] := coords * plot[[1, 2, 2]] / Reverse@dims;

Show[mp2, style[scaleToRaster[#, Dimensions@m2, mp2]& /@ marker2]]

Large matrix correct scale

$\endgroup$

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.