ggplot在图例中显示缺失值
我想在图例中显示某些类别,即使形状文件中不存在。例如,考虑以下示例:
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-60
、61-70
、91-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)
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
scale_fill_*
命令中使用drop = FALSE
:< img src="https://i.sstatic.net/7O70b.png" alt="在此处输入图像描述">
Use
drop = FALSE
in yourscale_fill_*
command: