ggplot2中点的不同颜色

时间:2016-02-20 04:26:47

标签: r ggplot2

我想用R绘制散点图。我使用ggplot2绘制图片:

data<-data.frame(x=runif(50),y=runif(50))
ggplot(data, aes(x,y))+geom_point()

但是我希望点根据“x”值有不同的颜色,点属于下面的“x”范围必须有不同的颜色。 [0,0.2),[0.2,0.4),[0.4,0.6],[0.6,0.8],[0.8,1]。

2 个答案:

答案 0 :(得分:1)

last_plot() +  aes(colour=cut(x, breaks = seq(0,1,by=0.2)))

答案 1 :(得分:1)

这可能是一种更好的方法,但这是我的解决方案:

# 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))

plot