4
$\begingroup$

The following command

DensityPlot[x y, {x, -3, 3}, {y, -3, 3}, PlotLegends -> Automatic, 
ColorFunction -> {"Rainbow"}, PlotRange -> {{-3, 3}, {-3, 3}}]

gives the following output:

Densityplot1.

I know that I can change the scale of the coloring in DensityPlot using PlotRange. I.e., the following command

DensityPlot[x y, {x, -3, 3}, {y, -3, 3}, PlotLegends -> Automatic, 
ColorFunction -> {"Rainbow"}, PlotRange -> {{-3, 3}, {-3, 3}, {-1, 1}}]

gives the following output:

DensityPlot2

In the second plot, the red color is assigned to the value $1$ and the purple color to the value $-1$. Question: is there a way to change the colors in the DensityPlot such that such that the red color is assigned to all values $\geq 1$, and similarly the purple color to $\leq 1$? So basically, I would like to obtain the second plot, where the four white corners are then colored red (upper left & lower right) or purple (upper right & lower left).

(Actually I'm using ListDensityPlot instead of DensityPlot, but I'm assuming this is similar.)

$\endgroup$
  • $\begingroup$ Look up Clip[] and the option setting ColorFunctionScaling. $\endgroup$ – J. M. is away Sep 1 '15 at 13:32
  • $\begingroup$ @Guesswhoitis. ClippingStyle is better suited to what he's asking for. $\endgroup$ – rcollyer Sep 1 '15 at 13:36
  • $\begingroup$ @rcollyer, forgot that option! Thanks for putting up an answer; what I had in mind was ColorFunction -> ColorData[{"Rainbow", {-1, 1}}, Clip[(* stuff *)]], and yours is certainly more idiomatic. $\endgroup$ – J. M. is away Sep 1 '15 at 13:43
  • $\begingroup$ @Guesswhoitis. I have to get that silver badge, eventually. :) $\endgroup$ – rcollyer Sep 1 '15 at 13:46
7
$\begingroup$

You are looking for ClippingStyle which accepts an arguments of the form

{gmin, gmax}

where gmin (gmax) is displayed for the lower (upper) clipped region. To match the colors exactly, you want to use ColorData, e.g.

ColorData[{"Rainbow", {-1, 1}}] /@ {-1, 1}

where I used the form allowing you to specify the range which I did for visual consistency. Of course, you could just use

ColorData["Rainbow"] /@ {0, 1}

regardless of range.

DensityPlot[x y, {x, -3, 3}, {y, -3, 3}, PlotLegends -> Automatic, 
 ColorFunction -> {"Rainbow"}, 
 PlotRange -> {{-3, 3}, {-3, 3}, {-1, 1}}, 
 ClippingStyle -> ColorData[{"Rainbow", {-1, 1}}] /@ {-1, 1}]

enter image description here

$\endgroup$
  • 4
    $\begingroup$ Exactly what I need, thanks! I was told once I should wait a bit in case a superior answer somehow appears, remind me if I forget to accept your answer in a day :P $\endgroup$ – ScroogeMcDuck Sep 1 '15 at 13:48
  • 1
    $\begingroup$ Increasing the PlotPoints (say PlotPoints -> 100) gives a smoother plot. $\endgroup$ – Bob Hanlon Sep 1 '15 at 22:30

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.