3
$\begingroup$

How can I define a ColorFunction for my ContourPlot using Piecewise? For example, after making a ContourPlot for this function:

p[x_, y_] := 1 - Sin[x]^2 Sin[y]^2;

I want to define my ColorFunction in a way that for example for 0 < p < 0.1 the plot have a different color than 0.1 < p < 0.2. An example of what I need is in the following plot: my example

where the colorbar at the right shows that each color corresponds to a value of p.

$\endgroup$
  • $\begingroup$ Doesn't it just work by default? ContourPlot[1 - Sin[x]^2*Sin[y]^2, {x, 0, Pi}, {y, 0, Pi}, PlotLegends -> Automatic, ColorFunction -> "DarkRainbow"] $\endgroup$ – Vitaliy Kaurov Mar 25 '13 at 23:00
  • $\begingroup$ @VitaliyKaurov Kaurov The thing is that I need to have control on the colors. In the plot that I have put as an example, e.g. dark orange corresponds to 0.8<p<0.9. ColorFunction -> "DarkRainbow" doesn't give me this option. $\endgroup$ – ZKT Mar 25 '13 at 23:03
8
$\begingroup$
myBlend[x_] := Blend[{Purple, Blue, Cyan, Green, Yellow, Orange, Red}, x]
ContourPlot[p[x, y], {x, 0, \[Pi]}, {y, 0, \[Pi]}, 
 Contours -> 25, ColorFunction -> myBlend]

or

myPiecewise[x_] := Piecewise[{{Red, 0 <= x <= 0.25}, 
  {Orange, 0.25 < x <= 0.75}, {Yellow, 0.75 < x <= 1}]
ContourPlot[p[x, y], {x, 0, \[Pi]}, {y, 0, \[Pi]}, 
  ColorFunction -> myPiecewise, ColorFunctionScaling -> False]

Remember to put ColorFunctionScaling -> False if you need precise control over the position of the colours.

<< PlotLegends`
ShowLegend[
  ContourPlot[2 p[x, y], {x, 0, \[Pi]}, {y, 0, \[Pi]}, 
     ColorFunction -> myPiecewise],
  {myPiecewise, 10, "0", "1", LegendPosition -> {1.1, 0}}]

guide/PlotLegendsPackage

Note: I work with version 8. In version 9 it appears to have been integrated: ref/BarLegend

$\endgroup$
  • $\begingroup$ Thanks a lot for your help. Do you know how can I build that color column at the right hand side of the plot in the question? I need to explain the colors using that. $\endgroup$ – ZKT Mar 25 '13 at 23:12
4
$\begingroup$

There's another syntax for Blend which lets you control the color-banding easily:

cf = Blend[{
    {0., Blue}, 
    {0.1, Green},
    {0.15, Black},
    {0.2, Red}, 
    {0.8, Purple},
    {0.95, Cyan}
    }, #1] & 

 DensityPlot[Sin[a] Sin[b],
   {a, -2 Pi, 2 Pi}, 
   {b, -2 Pi, 2 Pi}, 
   PlotPoints -> 250,
   ColorFunction -> cf ,
   MaxRecursion -> 2,
   ColorFunctionScaling -> False,
   ImageSize -> 500]

color function and densityplot

$\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.