6
$\begingroup$

The question is the following. Using Inset, we can insert a legend in a Plot (in a Graphic, in general). E.g.

scale = 2
step=0.05

marker=Graphics[{FilledCurve@Line[{{0,0},{2,0},{2,1},{0,1},{0,0}}]},ImageSize->100];
legendlabels={"a"};
legend=SwatchLegend[{Directive[Blue,[email protected]]},legendlabels,
LegendMarkers->ConstantArray[marker,1],
LegendMarkerSize->{{25,12.5}},LegendFunction->"Frame"];

epilog = {Inset[legend, Scaled[{1, 1} - step*{scale, 1}]]};

Show[Plot[Sin[x], {x, 0, 6 Pi}], Epilog -> epilog, Frame -> True, PlotRange -> {{0, 6 Pi}, {-1, 1}}, PlotRangePadding -> None]

By adjusting, in this case, the variables "scale" and "step" we can move the legend from the upper right corner towards the center of the plot.

However, if we knew the relative size of the axes of the rectangle bounding the legend, we could substitute it in "scale" and move the legend in such a way that it keeps the same distance from the x and y axes. Therefore...

Question

Is there a way to know the size of a legend constructed via SwatchLegend, LineLegend and the like?

Answer

Using Rasterize (Mathematica 10) we can get the size of the legend, and therefore do:

legend=SwatchLegend[{Directive[Blue,[email protected]]},legendlabels,
LegendMarkers->ConstantArray[marker,1],
LegendMarkerSize->{{25,12.5}},LegendFunction->"Frame"]

Rasterize[legend, "RasterSize"]
(* {51,31} *)

epilog = {Inset[legend, Scaled[{1, 1} - 0.05*{51/31, 1}]]}

i.e. take "scale" = 51/31 and "step" = 0.05. The result of

Show[Plot[Sin[x], {x, 0, 6 Pi}], Epilog -> epilog, Frame -> True, PlotRange -> {{0, 6 Pi}, {-1, 1}}, PlotRangePadding -> None]

is shown here (note "AspectRatio" = 1).

plot with legend from upper right corner

$\endgroup$

1 Answer 1

5
$\begingroup$

As of Mathematica 10, you can use the "RasterSize" element of Rasterize to get the size of almost anything in pixels, like so:

legend = SwatchLegend[{Directive[Blue, [email protected]]}, legendlabels, 
   LegendMarkers -> ConstantArray[marker, 1], 
   LegendMarkerSize -> {{25, 12.5}}, LegendFunction -> "Frame"];
Rasterize[legend, "RasterSize"]

(* {51, 31} *)
$\endgroup$

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.