Chloropleth:控制多边形填充

时间:2017-12-13 15:01:47

标签: r ggplot2

我上传了shapefile here

#First, read it in
library(rgdal)
pols <- readOGR(dsn="stack", layer="shapefile")

plot.df <- broom::tidy(pols, by="nr") %>% mutate(id = as.numeric(id))

#some values I'd like to plot
plot.df$value[plot.df$id==0] <- 4
plot.df$value[plot.df$id==1] <- 3
plot.df$value[plot.df$id==2] <- 3

library(ggplot2)
ggplot(plot.df, aes(x=long, y=lat))+
    geom_polygon(aes(fill=factor(value), group=group))+
    coord_fixed()+
    scale_fill_manual(values = c("red", "green", "blue", "orange"),
                breaks = c("1", "2", "3", "4"))

此代码应生成以下图表: enter image description here

问题是,我有另一个应该出现的多边形(以绿色着色)。

我想出了一个解决方法:

ggplot(plot.df, aes(x=long, y=lat))+
    geom_polygon(aes(fill=factor(value), group=group))+
    geom_polygon(data=subset(plot.df, id==0), aes(fill=factor(value), group=group))+
    coord_fixed()+ 
    scale_fill_manual(values = c("red", "green", "blue", "orange"),
                breaks = c("1", "2", "3", "4"))

enter image description here

但是,我确信有更优雅的解决方案。使用id作为建议here的分组变量会导致扭曲的多边形。

有没有人有其他想法?

1 个答案:

答案 0 :(得分:0)

多边形重叠,您可以设置alpha

ggplot(plot.df, aes(x = long, y = lat)) +
  geom_polygon(aes(fill = factor(value), group = group), alpha = .4)+
  coord_fixed() +
  scale_fill_manual(values = c("red", "green", "blue", "orange"), breaks = c("1", "2", "3", "4")) +
  theme(legend.position = 'none')

enter image description here