Search code examples
rr-sfgeography

How to plot circle with radius depending of a feature attribute with sf package?


I have these data representing coordinates on a map and a value for each point:

require(tidyverse)

df <- tribble(     ~ x,      ~ y,   ~ N,
               776025., 6990858.,   100,
               744220 , 6940666.,    75,
               774222., 6904024.,    55,
               719368., 6973708.,    30,
               735330., 7029420.,     1)

With the sf package I have managed to create geometry features from x and y columns:

require(sf)
(geom_column <- st_sfc(pmap(df[, 1:2], function(x, y) st_point(c(x, y)))))

and then compose those geometry features with the attribute feature N in a sf object:

(df <- st_sf(df[, 3], geometry = geom_column))

Then I can plot these 5 points:

plot(df)

enter image description here

Now I want to use circles with radius proportional to the N attributes instead of the color scale by default. But I do not find how to do that.


Solution

  • One approach (starting from your initial df, i.e. still withouth geometry column):

        scale_factor = 100 ## adjust as desired
    
        df |>
          st_as_sf(coords = c('x', 'y')) |>
          mutate(geometry = st_buffer(geometry, scale_factor *  N)) |>
          plot()
    

    another approach, letting ggplot take care of the scaling:

        library(ggplot2)
    
        df |>
          st_as_sf(coords = c('x', 'y')) |>
          ggplot(aes(geometry = geometry)) +
              geom_sf(aes(size = N))