简体   繁体   中英

color gradient in range of a ggplot with points and errorbars

I'm plotting a distribution of points and error bars in ggplot2.

ggplot(data=mydata,aes(x=x,y=m,group=scen,color=x)) +
geom_point(aes(shape=scen),size=5,na.rm=TRUE,
       position=position_dodge(width=5)) +
geom_errorbar(aes(x=x,ymax=u,ymin=l),na.rm=TRUE,
    position=position_dodge(width=5),width=1.25,size=1.1) +
theme_bw() 

I would like to color them with a gradient, but limiting the color ramp to a certain range. I managed to do that using:

ggplot(data=mydata,aes(x=x,y=m,group=scen,color=x)) +
geom_point(aes(shape=scen),size=5,na.rm=TRUE,
    position=position_dodge(width=5)) +
geom_errorbar(aes(x=x,ymax=u,ymin=l),na.rm=TRUE,
   position=position_dodge(width=5),width=1.25,size=1.1) +
theme_bw() +
scale_colour_gradient2(limits=c(-40, 40),
   low='darkred', mid='gray', high='darkblue') 

obtaining something like this :

I would like now to color the lower values (<-40) 'darkred', and the upper values (>+40) 'darkblue'. Any ideas?

How about something along the lines of

mydata <- transform(mydata,x_clamped=pmax(-40,pmin(40,x)))
ggplot(data=mydata,aes(x=x,y=m,group=scen,color=x_clamped)) + ...

? (No reproducible example given, so I haven't tested this.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM