Choropleth map in ggplot with polygons that have holes

后端 未结 4 534
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 05:17

I\'m trying to draw a choropleth map of Germany showing poverty rate by state (inspired by this question).

The problem is that some of the states (Berlin, for examp

4条回答
  •  一生所求
    2020-11-30 05:54

    Just to add another small improvement to @Ista's and @jhoward's answers (thanks a lot for your help!).

    The modification of @jhoward could be easily wrapped in a small function like this

    gghole <- function(fort){
            poly <- fort[fort$id %in% fort[fort$hole,]$id,]
            hole <- fort[!fort$id %in% fort[fort$hole,]$id,]
            out <- list(poly,hole)
            names(out) <- c('poly','hole')
            return(out)
    } 
    # input has to be a fortified data.frame
    

    Then, one doesn't need to recall every time how to extract holes info. The code would look like

        ggplot(map.df, aes(x=long, y=lat, group=group)) +
                geom_polygon(data=gghole(map.df)[[1]],aes(fill=poverty),colour="grey50")+
                geom_polygon(data=gghole(map.df)[[2]],aes(fill=poverty),colour="grey50")+
        # (optionally). Call by name
        #         geom_polygon(data=gghole(map.df)$poly,aes(fill=poverty),colour="grey50")+
        #         geom_polygon(data=gghole(map.df)$hole,aes(fill=poverty),colour="grey50")+
                scale_fill_gradientn(colours=brewer.pal(5,"OrRd"))+
                labs(x="",y="")+ theme_bw()+
                coord_fixed()
    

提交回复
热议问题