Make a 2D legend for a plot - bi-variate choropleth maps

后端 未结 3 2084
情深已故
情深已故 2021-02-10 23:48

I have been playing with bi-variate choropleth maps and have gotten stuck on how to create a 2d legend similar to the one by Joshua Stevens shown here:

To illus

3条回答
  •  花落未央
    2021-02-11 00:47

    Okay, last update. The white space between columns bugs me and the grid feature of cowplot will let us use a shrunken plot as our bi-variate legend, like so:

    library(ggplot2)
    library(cowplot)
    library(reshape2)
    #use color scheme shown here http://www.joshuastevens.net/cartography/make-a-bivariate-choropleth-map/
    bvColors=c("#be64ac","#8c62aa","#3b4994","#dfb0d6","#a5add3","#5698b9","#e8e8e8","#ace4e4","#5ac8c8")
    melt(matrix(1:9,nrow=3))
    legendGoal=melt(matrix(1:9,nrow=3))
    test<-ggplot(legendGoal, aes(Var2,Var1,fill = as.factor(value)))+ geom_tile()
    test<- test + scale_fill_manual(name="",values=bvColors)
    test<-test + theme(legend.position="none")
    #test<-ggdraw(test) + draw_text(text = "More Var 2 -->",x=0.91,y=0.58)
    #test<-ggdraw(test) + draw_text(text = "More Var 1 -->",x=0.84,y=0.5,angle=270)
    
    #create a plot that will be the legend itself
    lg<- test #would not be true when making a map
    lg<-lg + theme(axis.title.x=element_text(size=rel(1),color=bvColors[3])) + xlab("More Var2 -->")
    lg<-lg + theme(axis.title.y=element_text(size=rel(1),color=bvColors[3])) + ylab("More Var1 -->")
    lg<-lg+theme(axis.text=element_blank())
    lg<-lg+theme(line=element_blank())
    #put both plots on a grid
    ggdraw()+ draw_plot(lg,0.1,0.7,width=0.2,height=0.2) +draw_plot(test,0.3,0,width=.7,height=.7)
    

    Pretty, yes?

提交回复
热议问题