geom_ribbon 给数据分组 的覆盖面积上色

huron<-data.frame(year=1875:1972,level=as.vector(LakeHuron),level2=as.vector(LakeHuron))

 huron[1:50,2]<-huron[1:50,2]+100 #给第二列,1:50行每个值加100

 huron[50:90,2]<-huron[50:90,2]-100 #给第二列,50:90行每个值减100

View(huron)

 

h<-ggplot(huron,aes(year))

 h+geom_ribbon(aes(ymin=level,ymax=level2,fill=level>level2))+geom_line(aes(y=level))+geom_line(aes(y=level2))+scale_fill_manual(values=c("red","green"),name="fill") #一定留意geom函数里面aes指定。 这里fill是布尔值

 

 

 

>第二种优化实现方式

huron<-rbind(huron,huron[huron$year==1924,]) # 增加year=1924的数据

huron<-huron[order(huron$year),] # 将huron 按year 从小到大排序。 注:order 返回响亮从小到大值所在向量中的位置

huron$id<-1:nrow(huron) # 新增id列表示行数

huron$group<-ifelse(huron$id<=50,"A","B") # 新增group列,把50行之前的赋值A,之后的赋值B

View(huron)

 

 

 h<-ggplot(huron,aes(year)) #aes(x,y...) 按位置,一个参数时即是x

h+geom_ribbon(aes(ymin=level,ymax=level2,fill=group))+geom_line(aes(y=level))+geom_line(aes(y=level2))  #

 

>>更高阶的写法

 

 

h<ggplot()+geom_ribbon(data=huron[huron$level>=huron$level2,],aes(x=year,ymin=level,ymax=level2),fill="green")+geom_ribbon(data=huron[huron$level<=huron$level2,],aes(x=year,ymin=level,ymax=level2),fill="red")+geom_line(data=huron,aes(x=year,y=level))+geom_line(data=huron,aes(x=year,y=level2)) 

> h

 

 

 

注:

ggplot(data=NULL,mapping=aes(),...environment=parent.frame())  # R是承认位置参数的

geom_ribbon(mapping=NULL,data=NULL,position="identity",...na.rm=FALSE,orientation=NA,show.legend=NA,inherit.aes=TRUE,outline.type="both")

 #可以在geom_ribbon再定义data的,效果就是对data分组做不同的画图修饰如fill颜色

posted on 2022-05-14 22:26  BioinformaticsMaster  阅读(387)  评论(0编辑  收藏  举报

导航