Friday, February 25, 2011

How to color points by variable in R

Suppose we wan to plot x vs y according to the sign of z: if z > 0, we plot blue, while if z < 0, we plot red.

(1) Find the color code for "red" and "blue".
> grep("red",colors())
[1] 100 372 373 374 375 376 476 503 504 505 506 507 524 525 526 527 528 552 553 [20] 554 555 556 641 642 643 644 645
> grep("blue",colors())
[1] 2 26 27 28 29 30 31 42 43 44 45 46 62 73 107 121 122 123 124 [20] 125 128 129 130 131 132 399 400 401 402 403 430 431 432 433 434 435 438 439 [39] 440 441 442 461 473 477 491 546 562 563 564 565 566 589 590 591 592 593 594 [58] 595 596 597 598 615 616 617 618 619

(2) Generate our color vector.
> mycol<-563-(563-552)*(1-(sign(z)+1)/2)

(3) Plot using the color vector.
> plot(x, y, col=colors()[mycol])

No comments:

Visitors