rggplot2ggmapscatterpie

Change radius by site type geom_scatterpie


Is it possible to make certain pie charts larger than others based on a factor or grouping variable in a df? Or, does anyone have suggestions for how to differentiate groups within the data?

Here is code for creating the desired map, less the differentiation by factor level:

require(ggplot2)
require(ggmap)
require(scatterpie)
my_map <- ggmap(get_stadiamap(location <- c(165.6, 65, 165.75, 65.1),
                                zoom = 12, maptype = "stamen_terrain", crop = TRUE))

dat <- data.frame(site = c("station1", "station2", "station3", "station 4"),
                  site_type = factor(c("treatment", "treatment", "control",
                                     "control"), levels = c("treatment", "control")),
                  lat = c(65.06209, 65.0815, 65.04720, 65.05012),
                  lon = c(165.7265, 165.7257, 165.6616, 165.6840),
                  molerat = c(1,5,0,12),
                  porcupine = c(3,6,4,2),
                  muskrat = c(11,7,30,0),
                  lemming = c(2,8,0,0))

#plot
my_map +
  geom_scatterpie(data = dat, aes(x=lon, y=lat, r = 0.007
                                     ), color = "black",
                  cols = c(names(dat)[5:8]),
                  legend_name = "Species") + coord_equal(ratio = 1.5)

I cannot set a factor variable to r (radius) within aes(), as it leaves the map blank:

my_map +
  geom_scatterpie(data = dat, aes(x=lon, y=lat, r = site_type,
                                     ), color = "black",
                  cols = c(names(dat)[5:8]),
                  legend_name = "Species") + coord_equal(ratio = 1.5)

Is there a way?


Solution

  • The issue is that you are mapping a categorical variable on r which however requires a numeric value. Hence, to fix your issue add a new column or variable to your data which contains the radiuses for the site types. This variable can then be mapped on r inside aes.

    Note: I dropped the ggmap code as it is not important for your issue and makes the code more minimal and reproducible.

    library(ggplot2)
    library(scatterpie)
    #> scatterpie v0.2.4 Learn more at https://yulab-smu.top/
    
    dat <- dat |> 
      transform(
        r_site = ifelse(site_type == "treatment", .007, .014)
      )
    
    # plot
    ggplot() +
      geom_scatterpie(
        data = dat, aes(x = lon, y = lat, r = r_site), color = "black",
        cols = c(names(dat)[5:8]),
        legend_name = "Species"
      ) + 
      coord_equal(ratio = 1.5)