Reputation: 788
I want to draw a scatter plot with R. I use ggplot2 to draw the picture:
data<-data.frame(x=runif(50),y=runif(50))
ggplot(data, aes(x,y))+geom_point()
but I want the dots to have different colors according to the "x" value, the dots belongs to the following "x" ranges must have different colors. [0,0.2), [0.2,0.4), [0.4,0.6), [0.6,0.8),[0.8,1].
Upvotes: 0
Views: 1821
Reputation: 109
There's probably a better way to do this, but here's my solution:
# what we started with
data<-data.frame(x=runif(50),y=runif(50))
# create discretized variable z from x to determine plotted color.
# Since you wanted 5 levels, multiplied by 5 and took the floor, and then
# converted to a factor
z<-factor(floor((data$x)*5)) # or z<-factor(floor((data[,1])*5))
# add z to previous data frame and store in new variable dat
dat<-cbind(data,z)
# make pretty labels
lolim<-seq(0,0.8,0.2)
hilim<-seq(0.2,1,0.2)
lbls<-paste(lolim,'-',hilim)
# plot, changed x-axis ticks to show cutoff values
ggplot(dat,aes(x=x,y=y,color=z))+
geom_point()+
scale_color_hue(name='x',labels=lbls)+
scale_x_continuous(breaks=seq(0,1,0.2))
Upvotes: 1