Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

have plot points coloured on a spectrum in R

Tags:

plot

r

colors

I have a list of points that I want to play on a graph in R. In a bid to have 3 levels of information (X axis, Y axis and another) I want to plot the points on a graph and colour them on a scale for the 3rd variable. I have a percentage value for each point that I want displayed as the third variable (Z). So if A has a Z value of 0.95, I want it a bright red, but as B only has Z = 0.65, I want it dull red heading to blue. Values go from NA (which should be blue I suppose) to 0.99 (bright red).

Sample data:

1   1   0.02937715
2   1   0.05872889
3   1   0.08802983
4   1   0.11725462
5   1   0.14637799
6   1   0.17537475
7   1   0.20421981
8   1   0.23288821
9   1   0.26135518
10  1   0.28959607

The third column gives the Z values.

like image 778
cianius Avatar asked Apr 03 '13 15:04

cianius


1 Answers

Some reproducible data to play with would be helpful:

DF <- expand.grid(x=1:100, y=1:100)
DF$z <- abs(sin(DF$x/34) * cos(DF$y/22))

x and y are a grid from 1 to 100; z ranges between 0 and 1 (the function is nothing in particular, just something that stays between 0 and 1 and doesn't have extremely simple structure).

Base graphics

plot(DF$x, DF$y, col=rgb((colorRamp(c("blue", "red"))(DF$z))/255), pch=19)

enter image description here

ggplot2

library("ggplot2")
ggplot(DF, aes(x, y, colour=z)) +
  geom_point(shape=19) +
  scale_colour_gradient(low="blue", high="red")

enter image description here

like image 136
Brian Diggs Avatar answered Oct 17 '22 17:10

Brian Diggs