TransWikia.com

How to add SwatchLegend to a graph?

Mathematica Asked on December 24, 2020

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?

2 Answers

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

Correct answer by kglr on December 24, 2020

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

Plot[
 {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).

Answered by Rom38 on December 24, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP