Search code examples
rggplot2scalelegend

diverging size scale ggplot2


I am trying to map model/obs differences at locations in space. I have color mapped to the diff but I would also like to map size to diff. i'm currently mapping size to abs(diff) but it produces two different legends that I would like to combine. mapping size to diff creates small points for negative values and large points for positive values but I really only want the magnitude represented for over/under predictions. In case it makes a difference, I would also like the scales to be discrete. Thanks

Some test data:

so.df=data.frame(lat=runif(50,33,43),long=runif(50,-112,-104),diff=runif(50,-2,2))
    ggplot()+
        geom_point(data=so.df,aes(x=long,y=lat,color=diff,size=abs(diff)),alpha=0.8)+
scale_color_gradient2(low='red',mid='white',high='blue',limits=c(-0.6,0.6),breaks=c(-0.6,-0.4,-0.2,-0.1,0,0.1,0.2,0.6))+
        guides(color=guide_legend('SWE Differences (m)'),size=guide_legend('SWE Difference\nMagnitudes (m)'))+
        coord_cartesian(xlim=c(-112.5,-104.25),ylim=c(33,44))+
        theme_bw()

EDIT: to use a discrete color scale I'm using the following (open to suggestions)

so.df$cuts=cut_interval(so.df$diff,length=0.15)
ggplot()+
    geom_path(data=states,aes(x=long,y=lat,group=group),color='grey10')+
    geom_point(data=so.df,aes(x=long,y=lat,color=cuts,size=abs(diff)),alpha=0.8)+
    coord_cartesian(xlim=c(-112.5,-104.25),ylim=c(33,44))+
    scale_colour_brewer(type='div',palette='RdYlBu')+
    guides(color=guide_legend('SWE Differences (m)'),size=guide_legend('SWE Difference\nMagnitudes (m))+ 
    theme_bw()

Solution

  • If you map your sizes to your cuts column and use scale_size_manual you can get the diverging size scale you want.

    ggplot() + geom_point(data=so.df,aes(x=long,y=lat,size=cuts,color=cuts)) 
    + scale_size_manual(values =   
    c(8,6,4,2,1,2,4,6,8),guide="legend") + 
    coord_cartesian(xlim=c(-112.5,-104.25),ylim=c(33,44)) +   
    scale_colour_brewer(type='div',palette='RdBu')