# How can I threshold for a minimum value with MatrixPlot?

Looking at the Options for MatrixPlot, there doesn't seem to be a mechanism for lowerbound threshold - i.e. ignoring values that fall below a certain cutoff.

If my data set is very large, and I need a fast method of accomplishing this, would anyone have a recommendation?

• is a rule too slow? mp = RandomReal[{-1, 1}, {40, 60}]; and MatrixPlot[mp /. a_ /; (a < .4) -> Null] – gpap Jul 10 '13 at 12:14
• I'd use Chop. – rcollyer Jul 10 '13 at 12:20

To long for comment. Idea different than gpap's and rcollyer's:

n = 300;
s = SparseArray[{{1, 1} -> 5, {2, 2} -> 5, {3, 3} -> 5, {n, n} -> 5}]
+ Table[RandomReal[], {n}, {n}];

SparseArray[
Thread[Rule[#, s[[ ##]] & @@@ #]] &@Position[s, x_ /; x > 1, 2]
] // ArrayPlot


Edit: Faster than ReplaceAll. Slower than Chop but I think this is more flexible.

• @J.M. Please, do not accept so quickly :) – Kuba Jul 10 '13 at 12:40
• However, it's a good answer! – J.M. Jul 10 '13 at 14:12
• FYI: Table[RandomReal[], {n}, {n}] would be better written RandomReal[1, {n, n}] – Mr.Wizard Jul 10 '13 at 16:56
• @Mr.Wizard Indeed, thanks. – Kuba Jul 10 '13 at 17:23

I don't really see how Chop is (directly) applicable unless "minimum value" means absolute value, and replacement via patterns is always going to be slower than pure numerics. I think the flexible and fast function is Clip:

Clip[x, {min,max}, {vmin,vmax}] gives vmin for x < min and vmax for x > max.

Borrowing Bill's example:

m = RandomReal[{-1, 1}, {6, 6}];
Manipulate[MatrixPlot[Clip[m, {i, ∞}, {0, 0}]], {i, -1, 1}]


Move the slider to change the threshold value

m = RandomReal[{-1, 1}, {6, 6}];
Manipulate[MatrixPlot[Chop[m, i]], {i, 0, 1}]


Threshold[m, i] and ColorRules with PatternTest (_?(Abs@# < i &) or j_ /; Abs@j < i) give the same results as Chop[m, i].

SeedRandom[1]
m = RandomReal[{-10, 10}, {6, 6}];
Manipulate[Grid[{{Labeled[MatrixPlot[Chop[m, i], ImageSize -> 300],
Style["\nChop", 16], Top],
Labeled[MatrixPlot[Threshold[m, i], ImageSize -> 300],
Style["\nThreshold", 16], Top]},
{Labeled[MatrixPlot[m, ColorRules -> {_?(Abs@# <= i &) -> White}, ImageSize -> 300],
Style[Column[{"\nColorRules -> ", "{ _?(Abs @ # <= i&) \[Rule] White}"},
Alignment -> Center], 16], Top],
Labeled[MatrixPlot[m, ColorRules -> {j_ /; Abs@j <= i -> White}, ImageSize -> 300],
Style[Column[{"\nColorRules -> ", "{j_/; Abs@j <= i \[Rule] White}"},
Alignment -> Center], 16], Top]}}, Dividers -> All],
{{i, 4}, 0, 10}]


The setting ColorRules - {_?(# <= i &) -> White} gives the same result as Clip[m, {i, ∞}, {0, 0}]. Clip and ColorRules are more flexible in that they allow arbitrary conditions.

Labeled[MatrixPlot[m, ColorRules -> {_?(-1 <= # <= 4 &) -> White}, ImageSize -> 500],
Style[Column[{"\nColorRules -> ",  "{ _?(-1 <= # <= 4&) \[Rule] White}"},
Alignment -> Center], 16], Top]