1
$\begingroup$

Is there a way to label a region plotted using RegionPlot automatically, i.e. for the legend to appear inside the region without having to specify coordinates?

Alternatively, is it possible to show the legend corresponding to a subregion when I hover the mouse on that region?

$\endgroup$

1 Answer 1

3
$\begingroup$
ClearAll[tBar, teXt]

teXt[impregs_, colors_, t_] := Text[Framed[Style[impregs[[t, 1, 1]], 16, Bold, 
     Opacity[1], Darker@colors[[t]]], Background -> None, FrameStyle -> None], 
   Mean[RandomPoint[impregs[[t]], 200]]];

tBar[regs_, colors_] := Dynamic[TogglerBar[Dynamic[n], 
    Table[i -> SwatchLegend[{colors[[i]]}, {Style[TraditionalForm[regs[[i]]], ## & @@ 
       If[MemberQ[n, i], {14, Bold}, 12], "Panel", Opacity[1], colors[[i]], 
        Background -> None]}, LegendMarkerSize -> 16], {i, 1, Length@regs}], 
    Appearance -> {"Horizontal", "Framed"}, Background -> None]];

Example:

regs = {x^2 < (y - 2)^3 + 1, 2 (y + 1)^2 + (x - 3)^2 <= 9, x + y <= -2};
impregs = ImplicitRegion[#, {{x, -6, 6}, {y, -6, 6}}] & /@ regs;
colors = ColorData[97] /@ Range[5];

Dynamic[RegionPlot[Evaluate[MapIndexed[Tooltip[#, #2[[1]]]&, regs]], {x, -6, 6}, {y, -6, 6},
  PlotRange -> {{-6, 6}, {-6, 6}}, ImageSize -> 450, PlotRangeClipping -> False, 
  PlotLabel -> Mouseover[Invisible @ tBar[regs, colors], tBar[regs, colors]], 
  BoundaryStyle -> Thread[n -> Thickness[.01]],
  Epilog -> {teXt[impregs, colors, #] & /@ n}, 
  DisplayFunction -> (# /. Tooltip[p_, t_] :> Mouseover[p,
    {p, If[MemberQ[n, t], {}, teXt[impregs, colors, t]]}] &)], 
 Initialization :> {n := {}}]

enter image description here

$\endgroup$
1
  • $\begingroup$ Thank you @kglr. That is very elegant, indeed! $\endgroup$ Commented Dec 24, 2018 at 3:47

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.