0

I am trying to report how often a district is showing up in my bride price sample. But I think when a district does't have any reports or NAs, then the frequency == 0 so the district is still being coloured. I want to show districts with NAs as grey coloured. enter image description here

bp_dist1 <- joined1 |>
  group_by(ADM2_EN) |> 
  mutate(freq = n()) |> 
  ggplot() +
  geom_sf(aes(fill = freq), na.rm=T) +
  scale_fill_gradient(low = "coral", high = "coral4") +
  theme(rect = element_blank(), axis.text.x = element_blank(),
        axis.text.y = element_blank(), axis.ticks = element_blank(), 
        axis.title.x = element_blank(), axis.title.y = element_blank()) +
  guides(fill = guide_colourbar(
    title = "Frequency of bride price reports", title.theme = element_text(size = 8),
    label.theme = element_text(size = 7)
    ))
stefan
  • 90,330
  • 6
  • 25
  • 51
user
  • 23
  • 2
  • Related https://stackoverflow.com/questions/42365483/add-a-box-for-the-na-values-to-the-ggplot-legend-for-a-continuous-map – tjebo May 01 '23 at 21:08

1 Answers1

1

It's hard to know without the actual data you're using (if you post the data or a reproducible example it's easier to help :)), but I'm almost certain it's a data issue. Try running any(is.na(freq)) on the dataframe column you're using. I suspect it may come up FALSE, indicating that somewhere along the line, your NAs were removed or otherwise have been messed up.

If it comes up TRUE then you know you do in fact have the NA values in your dataframe and it's a plotting issue.

If you do have the NAs and it's a plotting issue, try adding the na.value argument to scale_fill_gradient:

library(sf)
# using nc as example dataset
nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

# make an integer column with some NA's
nc$var <- sample(
  c(sample(x = c(0:10), size = 94, replace = TRUE), rep(NA, 6))
)

# plot the data
ggplot(nc) +
  geom_sf(aes(fill = var)) + 
  scale_fill_gradient(low = "coral", high = "coral4", na.value = "green") +
  theme_void()

enter image description here

Although, without that na.value, ggplot() should still recognize the NA's. In my example it looks like this:

enter image description here

colebrookson
  • 831
  • 7
  • 18