Search code examples
rggplot2axis-labelsexpandr-sf

geom_sf: Relabeling Graticules with expand=FALSE


I create a spatial rectangle 25 x 20 and I only want to label the extremities (0, X) and (0, Y) when I plot it.
It works fine when coord_sf(expand=T) but I get an error message if expand=F.

The rectangle is defined as

library(sf)
x <- c(0, 25, 25, 0, 0)
y <- c(0, 0, 20, 20, 0)
poly.sf <- st_sf(geometry = st_sfc(st_polygon(list(matrix(c(x1,y1), ncol=2)))))

The following plot works fine

library(ggplot) 
ggplot() + 
geom_sf(data=poly.sf) +
scale_y_continuous(breaks=c(0,20), labels=c("0", "Y")) +
scale_x_continuous(breaks=c(0,25), labels=c("0", "X"))

But since I want no space before and after the extremities, I add

+ coord_sf(expand=FALSE)

I get the following error:
"Error: Breaks and labels along x direction are different lengths"
which makes no sense to me.

How can I get a plot with axes labeled (0, X) and (0, Y) with no space before or after the extremities ?


Solution

  • I have tried to create a custom function for labelling, try this:

    
    library(sf)
    x <- c(0, 25, 25, 0, 0)
    y <- c(0, 0, 20, 20, 0)
    poly.sf <- st_sf(geometry = st_sfc(st_polygon(list(matrix(c(x, y), ncol = 2)))))
    
    library(ggplot2)
    
    # Custom labelling functions
    labsy <- function(y) {
      y[y != 0] <- "Y"
      paste0(y, "")
    }
    
    labsx <- function(x) {
      x[x != 0] <- "X"
      paste0(x, "")
    }
    
    ggplot() +
      geom_sf(data = poly.sf) +
      scale_y_continuous(breaks = c(0, 20), labels = labsy) +
      scale_x_continuous(breaks = c(0, 25), labels = labsx) +
      coord_sf(expand = FALSE)
    

    enter image description here