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}]
Answer
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]]]
]
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
]
Comments
Post a Comment