首页 > 解决方案 > 保留图例中 ggplot 中地图的所有中断

问题描述

我正在使用地图,并且我正在努力将所有用于休息的钥匙都保留在传说中,即使没有任何案例落在这些休息时间。

我正在使用其他问题的一些代码,经过编辑以显示我的问题。老问题在这里:R Custom Color Scale for Plotting

在此示例中,没有州|县落入“1001 - 10000”区间,但我需要将该键保留在图例中。代码如下:

图例中缺少中断的地图

stateNames <- c("alabama", "alabama", "arizona", "arkansas", "california", 
                "colorado", "connecticut", "florida", "georgia")
countyNames <- c("autauga", "blount", "apache", "bradley", "orange", 
                 "boulder", "new haven", "flagler", "turner")
dataCol <- c(0, 5, 15, 50, 150, 1000, 500, 249, 30)

map.county <- map_data('county')
counties   <- unique(map.county[,5:6])
data_map <- merge(counties, data.frame(region=stateNames, 
                                       subregion=countyNames, 
                                       data1= dataCol),
                  by=c("region","subregion"), all.x=T, all.y=F
)

data_map$data1[which(is.na(data_map$data1))] <- 0


map.county <- data.table(map_data('county'))
setkey(map.county,region,subregion)
data_map <- data.table(data_map)
setkey(data_map,region,subregion)
map.df <- map.county[data_map]

map.df$brks <- cut(map.df$data1, 
                   breaks = c(0, 1, 10, 25, 100, 250, 1000, 10000), 
                   labels = c("0", "1 - 10", "11 - 25", "26 - 100", 
                              "101 - 250", "251 - 1000", "1001 - 10000"),
                   include.lowest = TRUE)

ggplot(map.df, aes(x=long, y=lat, group=group, fill=brks)) + 
  geom_polygon(colour = "grey", size = 0.001) +
  coord_map()  +
  expand_limits(x = map.county$long, y = map.county$lat) +
  scale_fill_brewer(palette = "YlOrRd") +
  theme_void() +
  theme(legend.position = "right")

标签: rdictionaryggplot2legend

解决方案


您可以简单地将参数添加drop = FALSEscale_fill_brewer

ggplot(map.df, aes(x=long, y=lat, group=group, fill=brks)) + 
  geom_polygon(colour = "grey", size = 0.1) +
  coord_map()  +
  expand_limits(x = map.county$long, y = map.county$lat) +
  scale_fill_brewer(palette = "YlOrRd", drop = FALSE) +
  theme_void() +
  theme(legend.position = "right")

在此处输入图像描述

它回答了你的问题吗?


推荐阅读