5
$\begingroup$

Is it possible to plot a function with two different colors? To illustrate, let's have:

Plot[Sin[x], {x, 0, 2 π}]

which plots a curve. And I would like it to be red from {x,0,π} and blue {x,π,2π}? I found the ColorFunction but I am not sure that it is capable of this, as the documentation says that it is given the y coordinate for Plot.

Even more, (actually this is the final goal), instead of different colours, I would like different styles, so let's say a solid line from {x,0,π} and dashed line from {x,π,2π}.

$\endgroup$
11
$\begingroup$

MeshShading

Plot[Sin[x], {x, 0, 2 Pi}, MeshFunctions -> {# &}, 
 Mesh -> {{Pi/2}}, MeshShading -> {Red, Directive[Dashed, Blue]}, 
 PlotStyle -> Thick]

Mathematica graphics

Two piecewise functions

Plot[{ConditionalExpression[Sin[x], x <= Pi], 
  ConditionalExpression[Sin[x], x >= Pi]}, {x, 0, 2 Pi}, 
 PlotStyle -> {Directive[Thick, Red], Directive[Thick, Dashed, Blue]}]

Mathematica graphics

Post - processing

Plot[Sin[x], {x, 0, 2 Pi}, PlotStyle -> Directive[Thick, Red]] /. 
 Line[x_] :> (With[{xx = (Pick[x, #[[1]] <= Pi & /@ x, #] & /@ {True, 
         False})}, {Line@xx[[1]], Dashed, Blue, Line@xx[[2]]}])

Mathematica graphics

ColorFunction

Plot[Sin[x], {x, 0, 2 Pi}, ColorFunctionScaling -> False, 
 ColorFunction -> Function[{x, y}, If[x <= Pi, Red, Blue]], 
 PlotStyle -> Thick]

Mathematica graphics

$\endgroup$
6
$\begingroup$

One more trick is to use Show

Show[Plot[Sin[x], {x, 0, Pi}, PlotStyle -> Red], 
 Plot[Sin[x], {x, Pi, 2 Pi}], PlotRange -> {{0, 2 Pi}, Automatic}]

enter image description here

$\endgroup$
1
$\begingroup$

Use ColorFunction with Function.

Plot[Sin[x], {x, 0, 2 Pi}, PlotStyle -> Thick, 
 ColorFunction -> Function[{x, y}, ColorData["Rainbow"][y]]]  

enter image description here

A rather quack way can be dividing you plots into segments with distinct style and combine them together.

 plot[l_, dl_] := Plot[Sin[x], {x, l 2 Pi, (l + dl) 2 Pi},
  PlotStyle -> Hue[l], PlotRange -> {{0, 2 Pi}, All}]
 dl = 0.01;
 Show[plot[#, # + dl] & /@ Range[0, 1 - dl, dl]]

enter image description here

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.