0
votes

I plotted a US map in which different counties are colored according to the value of a quantity called AQI. The code is the following:

my_data %>%
  ggplot() +
  geom_sf(mapping = aes(fill = AQI, geometry = geometry),
          color = "#ffffff", size = 0.05) +
  coord_sf(datum = NA) +
  scale_fill_continuous(low = "green", high = "orange", guide = guide_colorbar(nbin=10))
  labs(fill = "AQI")

The color bar next to the map displays a continuous gradient of colors from green to orange. What I really want, though, is the bar to display only one shade of green from 0 to 50; one shade of yellow from 51 to 100; and one shade of orange above 100. How can I do that?

1

1 Answers

0
votes

The colour scale is continuous as the AQI (Air Quality Index?) is most probably numeric/integer (it is impossible to tell without sample data).

You can make it categorical using the cut() function in base R:

# hypothetical AQI
AQI <- 0:200

AQI_cat <- cut(AQI, breaks = c(0, 50, 100, Inf), include.lowest = TRUE)
> table(AQI_cat)
AQI_cat
   [0,50]  (50,100] (100,Inf] 
       51        50       100 

Now we pass AQI_cat to the fill argument and then use scale_fill_manual() to specify the fill colours we want for each category:

my_data$AQI_cat <- AQI_cat

my_data %>%
  ggplot() +
  geom_sf(mapping = aes(fill = AQI_cat, geometry = geometry),
          color = "#ffffff", size = 0.05) +
  coord_sf(datum = NA) +
  scale_fill_manual(values = c("green", "yellow", "orange")) +
  labs(fill = "AQI")