plotting legends in Mathematica

Wombat picture Wombat · Aug 12, 2010 · Viewed 11.8k times · Source

How do you plot legends for functions without using the PlotLegends package?

Answer

the_one_smiley picture the_one_smiley · Sep 2, 2010

I, too, was disappointed by the difficulty of getting PlotLegend to work correctly. I wrote my own brief function to make my own custom figure legends:

makePlotLegend[names_, markers_, origin_, markerSize_, fontSize_, font_] := 
  Join @@ Table[{
    Text[
      Style[names[[i]], FontSize -> fontSize, font], 
      Offset[
        {1.5*markerSize, -(i - 0.5) * Max[markerSize,fontSize] * 1.25},
        Scaled[origin]
      ],
      {-1, 0}
    ],
    Inset[
      Show[markers[[i]], ImageSize -> markerSize],
      Offset[
        {0.5*markerSize, -(i - 0.5) * Max[markerSize,fontSize] * 1.25},
        Scaled[origin]
      ],
      {0, 0}, 
      Background -> Directive[Opacity[0], White]
    ]
  },
  {i, 1, Length[names]}
];

It is flexible, but not so easy to use. "names" is a list of strings to render in the legend; "markers" is a list with the same length as "names" of Graphics objects representing the plot markers or graphics to render; "origin" is a two-element list with the absolute horizontal and vertical position of the upper-left corner of the legend; "markerSize" is the number of points to scale the markers to; "fontSize" is the font size; "font" is the name of the font to use. Here is an example:

Plot[{x, x^2}, {x, 0, 2}, PlotStyle -> {Blue, Red},
  Epilog -> makePlotLegend[
    {x, x^2},
    (Graphics[{#, Line[{{-1, 0}, {1, 0}}]}]) & /@ {Blue, Red},
    {0.9, 0.3},
    12,
    12,
    "Arial"
  ]
]

generated image