# Plotting 3D piecewise function with distinct colors

I want to draw the following picture in Mathematica as shown below with distinct color for each section. • Well, did you try anything and, if yes, where did you get stuck?
– acl
Jul 16, 2014 at 11:25
• I used this code: Plot3D[-1/4 x^3, {x, -20, 20}, {y, 0, 30}, ColorFunction -> Function[{x}, Piecewise[{{Red, -20 <= x < -10}, {Orange, -10 <= x < 0}, {Yellow, 0 <= x <= 20}}]], PlotStyle -> Thick, ColorFunctionScaling -> False] Jul 16, 2014 at 11:32

Try using MeshShading:

Plot3D[
-(x - 12.5)^3,
{x, 0, 25},
{y, 0, 20},
MeshShading -> {Table[Hue[x], {x, 0, 1, 1/16}]}
]


The Table part generates sixteen different colors from the Hue color function. I did this because the image in this case had sixteen rows. If there are more rows than colors the colors will be reused cyclically. • Thanks you. and about dotted grid lines in background? Jul 16, 2014 at 12:13
• @MathMan I was away, it seems Mr.Wizard solved it in the meantime :) Jul 16, 2014 at 14:32

Building on Pickett's answer with a few more Options:

pl = Plot3D[-(x - 12.5)^3, {x, 0, 25}, {y, 0, 20},
MeshShading -> {Table[Hue[x], {x, 0, 1, 1/16}]},
BoxRatios -> 1,
Boxed -> False,
FaceGrids -> {{0, 1, 0}, {-1, 0, 0}, {0, 0, -1}},
FaceGridsStyle -> Directive[Thick, Gray, Dotted]
] It's not perfect but hopefully it points you in a useful direction.

An example for the legend was requested. One can use Inset to place a Graphics (or other) object in a 3D plot. As a rough illustration:

rec = Graphics[{Green, EdgeForm[Thick], Rectangle[{0, 0}, {50, 20}]},
ImageSize -> {50, 20}, PlotRangePadding -> 0];

lg = Framed[Row[{rec, Style["S", 18]}]];

Show[pl, Epilog -> Inset[lg, Scaled[{0.8, 0.8}]]] • I copied the wrong code for that particular graphic. Now corrected. Sorry for any confusion. Jul 16, 2014 at 13:16
• and about the Legend? Jul 16, 2014 at 16:48
• @MathMan Which version of Mathematica are you using? Jul 16, 2014 at 23:44
• I am using Mathematica 7 Jul 19, 2014 at 11:07
• @MathMan See update. Jul 19, 2014 at 11:45