14
$\begingroup$

Sin[x]

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

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

$\endgroup$

2 Answers 2

23
$\begingroup$
 Plot[Sin[x], {x, 0, 2 π}, PlotStyle -> Thick,
 ColorFunction -> Function[{x, y}, If[x < Pi, Red, Blue]],
 ColorFunctionScaling -> False,
 PlotRange -> {{0, 2 π}, {-1, 1}}]

or

 Plot[Sin[x], {x, 0, 2 π}, PlotStyle -> Thick,
 Mesh -> {{Pi}},
 MeshShading -> {Red, Blue},
 PlotRange -> {{0, 2 π}, {-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

$\endgroup$
2
  • $\begingroup$ Thank you! And if I want to make the blue region dashed? I tried MeshShading -> {Red, {Blue, Dashed}} without any luck.. $\endgroup$
    – Andrei
    Feb 4, 2013 at 13:14
  • 1
    $\begingroup$ you need to use Directive: MeshShading->{Red,Directive[Blue,Dashed]} $\endgroup$
    – kglr
    Feb 4, 2013 at 13:24
1
$\begingroup$

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

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