4
$\begingroup$

Is there any option that allows one to change the ticks and borders of the bar legend in a density plot to black?

enter image description here

$\endgroup$
2
$\begingroup$

You can use PlotLegends -> BarLegend[Automatic, FrameStyle->Black] instead of Automatic to color the frame (although as CE notes, the FrameStyle option will be colored red):

DensityPlot[
    Sin[x] Sin[y], {x,-4,4}, {y,-3,3},
    ColorFunction->"SunsetColors",
    FrameStyle->Black,
    PlotLegends->BarLegend[Automatic, FrameStyle->Black]
]

enter image description here

$\endgroup$
2
$\begingroup$

I don't see a way to style BarLegend from DensityPlot but there are some potential workarounds. (Carl has shown how to provide the settings I show below directly in DensityPlot.)

bar = BarLegend["Rainbow",
  FrameStyle -> Red,
  TicksStyle -> Darker@Green,
  LabelStyle -> Blue];

Legended[
 DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}],
 bar
 ]

Mathematica graphics

The coloring of some of the options to BarLegend indicate that they don't work but they do:

Mathematica graphics

produces the bar seen above, even though FrameStyle and TicksStyle are colored red. It's just something to be aware, it may mean that Wolfram Research aren't committed to making this work in future versions of Mathematica.

Another way to get more control of the color bar is to draw it yourself. Here's an example:

bar = ParametricPlot[
   {x, y}, {x, 0, 1}, {y, 0, 1},
   Frame -> True,
   FrameTicks -> {{None, All}, {None, None}},
   FrameStyle -> Red,
   FrameTicksStyle -> Darker@Green,
   PlotRange -> {{0, 1}, {0, 1}},
   ColorFunction -> (ColorData["Rainbow", #2] &),
   AspectRatio -> 10
   ];

Legended[
 DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}],
 bar
 ]

Mathematica graphics

$\endgroup$
  • $\begingroup$ Thanks! It is a hack, but is should do the job! $\endgroup$ – baker Apr 20 at 20:16
1
$\begingroup$

It is something of a hack, but you can steal the bar legend from ContourPlot. Like so.

  1. Make a contour plot and select and copy the vertical bar legend.

    ContourPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}, 
      ColorFunction -> "SunsetColors",
      PlotLegends -> Automatic]
    

    grab_bar

  2. Assign the copied graphic to a variable.

    bar

  3. Use the variable in your density plot.

    DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}, 
      ColorFunction -> "SunsetColors",
      FrameStyle -> Black,
      PlotLegends -> bar]
    

    plot

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.