Makayla Kelso
Makayla Kelso

Reputation: 61

Altering size of points on map in R (geom_sf) to reflect categorical data

I am creating a map to depict density of datapoints at different locations. At some locations, there is a high density of data available, and at others, there is a low density of data available. I would like to present the map with each data point shown but with each point a certain size to represent the density.

In my data table I have the location, and each location is assigned 'A', 'B', or 'C' to depict 'Low', 'Medium', and 'High' density. When plotting using geom_sf, I am able to get the points on the map, but I would like each category to be represented by a different size circle. I.e. 'Low density' locations with a small circle, and 'High density' locations with a larger circle.

I have been approaching the aesthetics of this map in the same way I would approach it as if it were a normal ggplot situation, but have not had any luck. I feel like I must be missing something obvious related to the fact that I am using geom_sf(), so any advice would be appreciated!

Using a very simple code:

ggplot() +
geom_sf(data = stc_land, color = "grey40", fill = "grey80") +
geom_sf(data = stcdens, aes(shape = Density) +
theme_classic()

I know that the aes() call should go in with the 'stcdens' data, and I got close with the 'shape = Density', but I am not sure how to move forward with assigning what shapes I want to each category.

Upvotes: 2

Views: 2506

Answers (1)

Jindra Lacko
Jindra Lacko

Reputation: 8699

You probably want to swap shape = Density for size = Density; then the plot should behave itself (and yes, it is a standard ggplot behavior, nothing sf specific :)

As your code is not exactly reproducible allow me to use my favorite example of 3 cities in NC:

library(sf)
library(ggplot2)


shape <- st_read(system.file("shape/nc.shp", package="sf")) # included with sf package

cities <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
                     x = c(-78.633333, -79.819444, -77.912222),
                     y = c(35.766667, 36.08, 34.223333),
                     population = c("high", "medium","low")) %>% 
  st_as_sf(coords = c("x", "y"), crs = 4326)  %>% 
  dplyr::mutate(population = ordered(population,
                                     levels = c("low", "medium", "high")))


ggplot() +
  geom_sf(data = shape, fill = NA) +
  geom_sf(data = cities, aes(size = population))

Note that I turned the population from a character variable to ordered factor, where high > medium > low (so that the circles follow the expected order).

enter image description here

Upvotes: 2

Related Questions