'removing missing values labels from ggplot
what I want appears to be simple but I can't figure it out: I want to take the NA values from my labs out. Problem is, it's my first time using the "na.value" argument, so I’m not quite sure how to proceed.
(btw, I can’t drop the NAs before plotting because the shapes that are not from the tourist regions will also disappear, and I need the full map.)
I have this code:
mun_tur_shape %>%
filter(abbrev_state == "BA") %>%
ggplot() +
geom_sf(aes(fill=TOURIST_REGION, colour=TOURIST_REGION)) +
scale_fill_manual(
na.value = "grey90"
values = c(viridis::inferno(13)),
aesthetics = c("fill", "colour")
) +
labs(fill = "Região Turística",
colour = "Região Turística"
) +
And this is how it looks: Plot with NA value
Does anyone know what I can do to omit them?
# here's an sf for reproducible example:
#install.packages(geobr)
df <- geobr::read_state()
df %>%
# creating NA values like my real dataset has
mutate(name_region=case_when(name_region=="Nordeste"~NA_character_,
TRUE~name_region)) %>%
ggplot() +
geom_sf(aes(fill=name_region, colour=name_region)) +
scale_fill_manual(
na.value = "grey90",
values = (viridis::inferno(4)),
aesthetics = c("fill", "colour")
) +
labs(colour = "Regions",
fill = "Regions")
Solution 1:[1]
My solution for this (see also NA values ?in choropleth plot legend with ggplot2 in R) is to add first a base layer with all the polygons (no aes) using the colors that I would want to use for NA. After that, you can overlay the layer with aes(). In practice, just add one line on your code
library(dplyr)
library(ggplot2)
library(geobr)
df <- geobr::read_state()
df %>%
# creating NA values like my real dataset has
mutate(name_region = case_when(
name_region == "Nordeste" ~ NA_character_,
TRUE ~ name_region
)) %>%
# Create map
ggplot() +
# Add this line a base layer with no aes, but a NA fill color
geom_sf(fill = "grey50", color = "grey50") +
# end
geom_sf(aes(fill = name_region, colour = name_region)) +
scale_fill_manual(
na.value = "grey90",
values = (viridis::inferno(4)),
aesthetics = c("fill", "colour"),
na.translate = FALSE
) +
labs(
colour = "Regions",
fill = "Regions"
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dieghernan |

