In a Plot3D I want to change the displayed value range, see the following example. The function generates the values {-1,1}, they are displayed correctly on the z-axis within {-2, 2}, but the color coding is not correct, because it still runs from {-1,1} instead of {-2,2}.

Plot3D[ Sin[x*y], {x, -Pi, Pi}, {y, -Pi, Pi},
ColorFunction -> "Rainbow", PlotRange -> {-2, 2},
PlotLegends -> {Placed[BarLegend[{"Rainbow", {-2, 2}}, None,
LegendLabel -> Placed["Val", Above]], Right]}]

Output, color scheme does not match

How do I match the value and color ranges in the plot and the legend to {-2, 2}?


1 Answer 1


Creating a ColorFunction that runs through the Rainbow colors over the range (-2,2):

cf = Function[x, ColorData["Rainbow"]@Rescale[x, {-2, 2}]];
legend = BarLegend[{cf, {-2, 2}}, None, LegendLabel -> Placed["Val", Above]];

Plot3D[Sin[x*y], {x, -Pi, Pi}, {y, -Pi, Pi},
 PlotRange -> {-2, 2},
 ColorFunction -> Function[{x, y, z}, cf[z]],
 ColorFunctionScaling -> False,
 PlotLegends -> legend

Mathematica graphics

  • $\begingroup$ I works, still I don't understand why. I'll try to figure it out. $\endgroup$
    – osx
    Aug 26, 2019 at 18:37

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.