Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Sin[x]

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

Is there a simpler way of doing this? Especially, one that does not require repeating the Plot command 2 times ;)

share|improve this question
up vote 18 down vote accepted
 Plot[Sin[x], {x, 0, 2 \[Pi]}, PlotStyle -> Thick,
 ColorFunction -> Function[{x, y}, If[x < Pi, Red, Blue]],
 ColorFunctionScaling -> False,
 PlotRange -> {{0, 2 \[Pi]}, {-1, 1}}]

or

 Plot[Sin[x], {x, 0, 2 \[Pi]}, PlotStyle -> Thick,
 Mesh -> {{Pi}},
 MeshShading -> {Red, Blue},
 PlotRange -> {{0, 2 \[Pi]}, {-1, 1}}]

or

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

enter image description here

share|improve this answer
    
+1 for covering the bases – Mr.Wizard Feb 4 '13 at 13:04
    
Thank you! And if I want to make the blue region dashed? I tried MeshShading -> {Red, {Blue, Dashed}} without any luck.. – Andrei Feb 4 '13 at 13:14
    
you need to use Directive: MeshShading->{Red,Directive[Blue,Dashed]} – kglr Feb 4 '13 at 13:24

Not a simpler way:

plt = Plot[Sin[x], {x, 0, 2 \[Pi]}];
{d, opt} = {Cases[plt, Line[x_] -> x, Infinity][[1]], plt[[2]]};
{r, b} = GatherBy[d, #[[1]] <= Pi &];
Graphics[{Thick, {Red, Line@r}, {Blue, Line@b}}, opt]
(*ListLinePlot[{r,b},PlotStyle->{{#,Red},{#,Blue}}&@Thick]*)

enter image description here

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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