6
$\begingroup$

I have the following problem. I'd like to add a legend to MatrixPlot. Each colour should have a legend entry. I used PlotLegends, which in principle works. However, if I use more than five colours, this doesn't work anymore.

a = RandomInteger[{1, 6}, {50}];
MatrixPlot[{a}, ColorRules ->
                 {1 -> Red, 2 -> Blue, 3 -> Green, 4 -> Gray,5->Yellow,6->Orange}]
$\endgroup$

2 Answers 2

6
$\begingroup$

When Automatic fails the same thing can, luckily, be done manually:

rules = {1 -> Red, 2 -> Blue, 3 -> Green, 4 -> Gray, 5 -> Yellow, 6 -> Orange};

a = RandomInteger[{1, 6}, {50}];
MatrixPlot[
 {a},
 ColorRules -> rules,
 PlotLegends -> SwatchLegend[rules[[All, 2]], rules[[All, 1]]]
 ]

Example legends

A horizontal version (this is an update in response to Bob's new answer) can be achieved thus:

PlotLegends -> Placed[
  SwatchLegend[rules[[All, 2]], rules[[All, 1]]],
  Bottom
  ]

Horizontal legends

$\endgroup$
2
$\begingroup$
a = RandomInteger[{1, 6}, {50}];

colors = {1 -> Red, 2 -> Blue, 3 -> Green, 4 -> Gray, 5 -> Yellow, 
   6 -> Orange};

Column[{
  MatrixPlot[{a},
   ColorRules -> colors,
   ImageSize -> 400],
  SwatchLegend[
   colors[[All, 2]], 
   colors[[All, 1]],
   LegendLayout -> "Row"]},
 Alignment -> Center]

enter image description here

$\endgroup$
0

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.