how to create a point graph(ListPlot?), where the positive values will be BLUE, negative RED and 0 values will be green?
Thanks.
Answer
The first solution is a basic one, but it does the trick. For a second solution involving ColorFunction
, see below.
I assume that you have a list of points, such as
ptList = {{1, -2}, {2, 5}, {3, 6}, {4, 0}, {5, 1}, {6, -4}, {7, -6.5}, {8, 2}, {9, 0}, {10, 5}};
and that you are interested in whether the second coordinate is postive, negative or zero. First you can extract the negative and positive elements from the list:
listNeg = Cases[ptList, x_ /; Negative[x[[2]]]]
(* {{1, -2}, {6, -4}, {7, -6.5}} *)
listPos = Cases[ptList, x_ /; Positive[x[[2]]]]
(* {{2, 5}, {3, 6}, {5, 1}, {8, 2}, {10, 5}} *)
The rest is automatically zero:
listZero = Complement[ptList, Join[listNeg, listPos]]
(* {{4, 0}, {9, 0}} *)
Then you can plot the three different lists, each with their own color:
ListPlot[{listPos, listNeg, listZero}, PlotStyle -> {Blue, Red, Green}]
which gives the result:
Alternatively, you can put everything into one ListPlot
command, which may save some memory when you are dealing with large lists. In that case, you can no longer use Complement
to find the zero elements, but you should check for them instead:
ListPlot[{Cases[ptList, x_ /; Positive[x[[2]]]], Cases[ptList, x_ /; Negative[x[[2]]]], Cases[ptList, x_ /; x[[2]] == 0]}, PlotStyle -> {Blue, Red, Green}]
This gives you the same result as before.
Edit: a second solution using ColorFunction
Based on the question that funnypony referred to and based on an answer to this question, here is a second solution.
First you define your own ColorFunction
using Piecewise
myColorFunc[x_] := Piecewise[{{Blue, x > 0}, {Green, x == 0}, {Red, x < 0}}]
Then, you use ListLinePlot
with a replacement rule
ListLinePlot[ptList, ColorFunction -> myColorFunc, ColorFunctionScaling -> False] /. Line[arg___] :> Point[arg]
which gives the same result as before, albeit with square plot markers instead of round ones.
Comments
Post a Comment