ggplot在图例中显示缺失值

89_*_*ple 1 r legend ggplot2

我想在图例中显示某些类别,即使形状文件中不存在。例如,考虑下面的例子:

library(raster)
library(sp)
library(sf)
library(viridis)

shp <- getData('GADM', country = "FRA", level = 1)
shp_sf <- st_as_sf(shp)

temp_df <- 
data.frame(NAME_1 = shp@data$NAME_1,
           value = c(1, 15, 28, 80, 32, 90, 29, 12, 43, 44, 27, 2, 6))

temp_df$value_cut <- cut(temp_df$value, 
                     breaks = c(0,11, 21, 31, 41, 51, 61, 71, 81, 91, 100),
                     labels = c("1-11", "11-21", "21-31", "31-41", "41-51","51-61","61-71","71-81","81-91","91-100"),
                     include.lowest = TRUE)

   shp_sf_join <- sp::merge(shp_sf, temp_df, "NAME_1")

   ggplot(shp_sf_join) + 
   geom_sf(aes(fill = value_cut)) +
   coord_sf() +
   viridis::scale_fill_viridis(name="", option = "G", discrete=T) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在图例中,我想要51-60, 61-7091-100以及当前丢失的,因为它们不在数据框中。谢谢。

Maë*_*aël 5

drop = FALSE在您的命令中使用scale_fill_*

ggplot(shp_sf_join) + 
  geom_sf(aes(fill = value_cut)) +
  coord_sf() +
  viridis::scale_fill_viridis(name="", option = "G", discrete=T, drop = FALSE) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述