I created a random graph with each vertex colored randomly.

I would like to add a SwatchLegend to the graph to indicate the value corresponding to a color. How can I do that?

Here's my code for the graph.

color = Map[# -> ColorData[3][RandomInteger[{1, 5}]] &, Range[100]];
g1 = RandomGraph[{100, 500}, VertexStyle -> color, VertexSize -> 1.5]

Here's my code for the legends.

legend = SwatchLegend[Table[ColorData[3][i], {i, 1, 5}], Automatic];

How can I combine the two?


You can use Legended:

Legended[g1, legend]

enter image description here

Alternatively, you can use the option Epilog:

RandomGraph[{100, 500}, VertexStyle -> color,  VertexSize -> 1.5, 
 Epilog -> Inset[legend, Scaled @ {1.1, .5}], ImagePadding -> 40]

enter image description here


In general, you can use any type of legends inside the plotting routines:

 {Sin@x, Cos@x}, {x, -Pi, Pi},
 PlotStyle -> {Red, Blue},
 PlotLegends -> 
  Placed[SwatchLegend[{Red, Blue}, {"Sin", "Cos"}], Right]

However, the kglr's way allows making legends for any objects (like arbitrary graphics).


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.