ggplot在图例中显示缺失值

发布于 2025-01-11 12:13:45 字数 1072 浏览 0 评论 0原文

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

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) 

在此处输入图像描述

在图例中,我想要 51-6061-7091-100< /code> 以及哪些是目前缺失,因为它们不在数据框中。 谢谢。

I want to display certain categories in the legend even though there are not present in the shapefile. For e.g. consider the below example:

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) 

enter image description here

In the legend, I want 51-60, 61-70, 91-100 as well which are currently missing since they are not in the dataframe.
Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风苍溪 2025-01-18 12:13:45

scale_fill_* 命令中使用 drop = FALSE

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

< img src="https://i.sstatic.net/7O70b.png" alt="在此处输入图像描述">

Use drop = FALSE in your scale_fill_* command:

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

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文