5
$\begingroup$

Using ColorRules with MatrixPlot, how does one get a hatching pattern in one of the cells?

For example, consider the data,

data = { {1, 2, 1}, {2, 2, 3} }

And now I consider the MatrixPlot,

MatrixPlot[data,
 ColorRules -> { 
   1 -> Blue, 
   2 -> Red, 
   3 -> Purple 
   }
 ]

matrixplot_example

Question: For the cell with the value 3 and currently with the color Purple, how can I get it to have a Purple color with a hatched pattern?

$\endgroup$
  • $\begingroup$ Somewhat related mathematica.stackexchange.com/q/31221/193 $\endgroup$ – Dr. belisarius Oct 29 '15 at 18:58
  • $\begingroup$ @belisariusisforth Thanks. I took a look at that link. Perhaps I'm completely missing something, but a "direct" fix is to replace Purple above in ColorRules with Graphics[{Black, Line[{{0, 0}, {1, 1}}]}] (I can fudge with the color later; the hatching is most important to me). But with that, I simply get this weird maroon color with no hatching. And even if I switch out Black to, say, Yellow in the above, there is no effect. $\endgroup$ – user32416 Oct 29 '15 at 19:08
  • 1
    $\begingroup$ As of v9 Mathematica haven't had direct support for hatching. Don't know if they did something about it later $\endgroup$ – Dr. belisarius Oct 29 '15 at 19:15
  • 2
    $\begingroup$ Related: "Generating hatched filling using Region functionality." $\endgroup$ – Alexey Popkov Oct 30 '15 at 5:37
11
$\begingroup$

As belisarius said, there is no current support for hatching but you could use a graphics overlay as a workaround.

First create the desired pattern and texture a Polygon with it:

t = Table[{0, n}, {n, -1, 1, 0.1}];

g[c_] := Graphics[{AbsoluteThickness[8], Line /@ Transpose[{t, t + 1}]}, 
    PlotRange -> {{0, 1}, {0, 1}}, Background -> c];

pattern2[p_, c_] := Graphics[{Texture[g[c]], Polygon[{
     {p[[1]] - 1, p[[2]] - 1},
     {p[[1]], p[[2]] - 1},
     {p[[1]], p[[2]]},
     {p[[1]] - 1, p[[2]]}},
    VertexTextureCoordinates -> {{0, 0}, {0, 1}, {1, 1}, {1, 0}}
    ]}]

pattern2[{1, 1}, Purple]

enter image description here

Create a function to place the pattern over any field of a given value n. matrixLength is the length of the input data, c the color.

overlay[patternFunc_, n_, c_, matrixLength_] := 
  Show[patternFunc[#,c] & /@ ({#2,matrixLength + 
     1 - #1} & @@@ Position[data, n])];

Example:

plot = MatrixPlot[data, ColorRules -> {1 -> Red, 2 -> Orange, 3 -> Purple}]

enter image description here

Show[
 plot,
 overlay[pattern2, 3, Purple, Length@data]
 ]

enter image description here

Not the most elegant/efficient solution but it might be useful as a starting point.

$\endgroup$
  • $\begingroup$ Very useful! Thanks! $\endgroup$ – user32416 Oct 29 '15 at 20:06

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.