oswaldosantos / ggsn

R package to add north symbols and scale bars to maps created with ggplot or ggmap
http://oswaldosantos.github.io/ggsn/
GNU General Public License v2.0
161 stars 9 forks source link

Facets with numeric values #31

Closed statnmap closed 5 years ago

statnmap commented 6 years ago

I wanted to show scalebar on only one of the facets, but my variable is numeric (years). In that case, selecting a facet adds a new empty facet. I think this maybe due to the transformation to factors in your code. Maybe, you may want to use as.factor(as.character(...)) at some places.
Example:

library(dplyr)
library(ggsn); library(sf)
dsn <- system.file('extdata', package = 'ggsn')

# Map in geographic coordinates
map <- st_read(dsn, 'sp', quiet = TRUE)
map2 <- map %>% 
  mutate(years = as.numeric(nots) + 2000)

ggplot(map2, aes(fill = nots)) +
  geom_sf() +
  blank() +
  facet_grid(~years) + 
  north(map2) +
  scalebar(map2, dist = 5, dd2km = TRUE, model = 'WGS84',
           facet.var = "years", facet.lev = '2001')

numeric

oswaldosantos commented 6 years ago

scalebar does not inherit from ggplot and I think this is the problem. A workaround is:

map2 <- map %>% 
  mutate(years = as.factor(as.numeric(nots) + 2000))
statnmap commented 6 years ago

I think we need to look around the following layer implementation, but for now I did not get how it works really:

red_points <- function(mapping = NULL, 
                   data = NULL, stat = "identity", 
                   position = "identity", 
                   ..., na.rm = FALSE, show.legend = NA, 
                   inherit.aes = TRUE){

  layer(data = data, mapping = mapping, stat = stat, geom = GeomPoint, 
        position = position, 
        show.legend = show.legend, inherit.aes = inherit.aes, 
        params = list(na.rm = na.rm, color = "red", ...))

}

ggplot(iris) +
  aes(Sepal.Length, Sepal.Width) +
  red_points()

http://ggplot2.tidyverse.org/articles/extending-ggplot2.html

oswaldosantos commented 6 years ago

I agree. I'm not sure if we would need to create a new geom or stat.