Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Color-fill ggplot2 maps with a single color

Is there a way to color-fill counties with a NON-ZERO n with a single color (ex. green) AND possibly put a colored dot with a single color (ex. red) for counties with a NON-ZERO n in the middle of the counties?

library("sf")
library("tigris")
library("ggplot2")

me <- counties("Maine", cb=TRUE, class="sf")

me$n <- rep(0:3, each = 4)

ggplot(me, aes(fill = n, label = n)) + 
  geom_sf() +
  scale_fill_gradient(low = "yellow", 
                      high = "red",
                      na.value = "gray90") +
  theme_void()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you want one fill color for counties with a non-zero n then map the condition n > 0 on the fill aes and set your desired colors for zero and non-zero counties using scale_fill_manual:

library("sf")
#> Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
library("tigris")
#> To enable caching of data, set `options(tigris_use_cache = TRUE)`
#> in your R script or .Rprofile.
library("ggplot2")

ggplot(me, aes(fill = n > 0, label = n)) +
  geom_sf() +
  scale_fill_manual(
    values = c("yellow", "green")
  ) +
  theme_void()

And to add a dot in the center you can use sf::st_centroid:

centroids <- sf::st_centroid(me) |> 
  dplyr::filter(n > 0)

ggplot(me, aes(fill = n > 0, label = n)) +
  geom_sf() +
  geom_sf(data = centroids, color = "red") +
  scale_fill_manual(
    values = c("yellow", "green")
  ) +
  theme_void()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading