Skip to main content

plotting - Hatching pattern in ColorRules for MatrixPlot


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?



Answer



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.


Comments