4
$\begingroup$
lgnds = BarLegend[{{Red, White, Blue}, {-1, 1}}, 
  Ticks -> {{-1, Style["-1", 13, Black]}, {0, 
     Style["0", 13, Black]}, {1, Style["1", 13, Black]}}, 
  LegendMarkerSize -> 150]

DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}, 
 ColorFunction -> (Blend[{Red, White, Blue}, Rescale[#, {-1, 1}]] &), 
 ColorFunctionScaling -> False, PlotLegends -> Placed[lgnds, Above]]  

In the cod above the White color in the BarLegend must be at 0, why is it shifted?

enter image description here

$\endgroup$
1
  • 1
    $\begingroup$ DensityPlot seems to be rescaling the legend. Happens with ContourPlot, too. I don't see why it should do that. Probably a bug. $\endgroup$
    – Michael E2
    Sep 6, 2020 at 18:09

2 Answers 2

1
$\begingroup$

If you add the option ColorFunctionScaling -> True in BarLegend the anomaly disappears:

lgnds2 = BarLegend[{{Red, White, Blue}, {-1, 1}}, 
  ColorFunctionScaling -> True, 
  Ticks -> {{-1, Style["-1", 13, Black]}, {0, 
     Style["0", 13, Black]}, {1, Style["1", 13, Black]}}, 
  LegendMarkerSize -> 150]

enter image description here

DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}, 
 ColorFunction -> (Blend[{Red, White, Blue}, Rescale[#, {-1, 1}]] &), 
 ColorFunctionScaling -> False, PlotLegends -> Placed[lgnds2, Above]]

enter image description here

The same issue arises in ContourPlot and it is also fixed using lgnds2:

enter image description here

$\endgroup$
5
$\begingroup$

Here's a workaround:

Legended[
 DensityPlot[Sin[x] Sin[y], {x, -4, 4}, {y, -3, 3}, 
  ColorFunction -> (Blend[{Red, White, Blue}, 
      Rescale[#, {-1, 1}]] &), 
  ColorFunctionScaling -> False],
Placed[Append[
  lgnds, {LegendLayout -> "Row", Charting`TickSide -> Left}],
 Above]]
$\endgroup$
2
  • $\begingroup$ one more thing please, how can I make the number in the BarLegend on the top as in the original plot? $\endgroup$ Sep 6, 2020 at 18:28
  • 1
    $\begingroup$ @HD2006 Add another option: Append[lgnds, {LegendLayout -> "Row", ChartingTickSide -> Left}]` $\endgroup$
    – Michael E2
    Sep 6, 2020 at 18:38

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.