Home > Blockchain >  Make Raster Fill Extent of Plot with ggplot
Make Raster Fill Extent of Plot with ggplot

Time:12-14

I have a raster layer that is larger than my plotting area. I'd like to plot a smaller section of the raster (and other layers), so I'd like to set the plotting area using xlim() and ylim() in ggplot.

However, setting the plotting area in that way clips the raster to the exact xlim and ylim, instead of the actual extent of the plot. That leaves an ugly border around the raster, but none of the other layers. Is there a better way to set the limits of a plot so that the raster isn't cut off?

Here's an example:

library(USAboundaries)
library(elevatr)
library(tidyverse)

states <- us_states(states = c("AL", "FL", "GA", "SC"))

se.elevations <- get_elev_raster(locations = states, z = 7, clip = "locations") 

se.elevation.df <- raster::as.data.frame(se.elevations, xy = TRUE) %>%
  rename(elevation =  3) %>%
  na.omit() %>%
  filter(elevation >= 0)

xlimit <- c(-87, -80)
ylimit <- c(29, 34)

ggplot() 
  geom_tile(data = se.elevation.df, aes(x = x, y = y, fill = elevation)) 
  scale_fill_gradientn(colours= c("gray", "black")) 
  geom_sf(data = states, fill = NA) 
  xlim(xlimit) 
  ylim(ylimit)

As you can see, the raster is cut off, but the states continue to the edge of the plot. Ugly!

CodePudding user response:

As a general rule, if you want to zoom on a part of your plot set the limits via the coord, i.e. in your case coord_sf:

library(ggplot2)

ggplot() 
  geom_tile(data = se.elevation.df, aes(x = x, y = y, fill = elevation)) 
  scale_fill_gradientn(colours= c("gray", "black")) 
  geom_sf(data = states, fill = NA) 
  coord_sf(xlim = xlimit, ylim = ylimit)

enter image description here

  • Related