Okey, so I have this code that took super long time to plot. It's a density plot and let's say that I would like to change to position of the BarLegend of the plot. I want to do this without having to redo the plot

As an example. Let's say we have the plot

p1 = DensityPlot[Sin[x] Sin[y], {x, -6, 6}, {y, -2, 2},
  ImageSize -> {600, 200},
  AspectRatio -> Automatic,
  PlotLegends -> Placed[BarLegend[Automatic,
     LegendMarkerSize -> {550, 30}
     ], Above]

and I want the BarLegend below instead of above the plot. How can I do this after the plot?

I've tried various methods

p1 /. PlotLegends -> Placed[BarLegend[Automatic,
LegendMargins -> {{0, 20}, {-15, 0}},
LegendMarkerSize -> {500, 30}
], Below]


Show[p1, PlotLegends -> Placed[BarLegend[Automatic,
LegendMargins -> {{0, 20}, {-15, 0}},
LegendMarkerSize -> {500, 30}
], Below]]

Nothing works.


2 Answers 2

p1 /. Placed[a_, Above, b_] :> Placed[a, Below, b]

or (a bit more robust)

ReplacePart[p1, {-1, 2} -> Below]

General hint: Apply InputForm onto the graphics object p1 in order figure out what exactly to replace.

  • $\begingroup$ Thanks! Do you know how can I determine the coordinates of the thing that I want to change using InputForm? Like How did you know InputForm[p1][[-1,2,2]] corresponded to Above? $\endgroup$ Mar 2, 2018 at 10:47
  • $\begingroup$ I knew that legends get wrapped by Placed and appear as second in Legended expressions. From where I anticipated that? I really looked at the output of InputForm[p1]... Also Hold /@ p1 would have helped... After seeing that it is about an Above, we can find its position with Position[p1, Above]. $\endgroup$ Mar 2, 2018 at 11:04

If Above appears only in relation to PlotLegends in p1:

p1 /. Above -> Below (* or *)
Block[{Above = Below}, p1]

enter image description here


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.