Home > Software engineering >  ggplot2 overwrites plot limits
ggplot2 overwrites plot limits

Time:02-03

I have two shapefiles, which I would like to plot into a given plot extent. One of the shapefiles exceeds the extent and when plotted it automatically overwrites the limits of the extent. This happens when loading the shapefiles using the terra package and plotting it using the tidyterra functions, but it is not an issue when reading the shapefiles using the old readOGR function and ploting it using the core ggplot2 functions.

# libraries
library(terra)
library(tidyterra)
library(ggplot2)
library(ggspatial)
library(raster)
library(sp)
library(sf)
library(rgdal)

EXAMPLE 1 - I don't want this

# read shapefiles
SHP1 <- terra::vect('file1.shp')
SHP2 <- terra::vect('file2.shp')

# plot
ggplot()   
  coord_equal(ylim=c(100000,800000))  
  geom_spatvector(data=SHP1,fill=NA,color='grey',inherit.aes=T)  
  geom_spatvector(data=SHP2,fill=NA,color='green',size=1)

enter image description here

EXAMPLE 2 - I want this

# read shapefiles
SHP1 <- terra::vect('file1.shp')
SHP2 <- terra::vect('file2.shp')

ggplot()   
  coord_equal(ylim=c(100000,800000))  
  geom_polygon(SHP1,mapping=aes(x=long,y=lat,group=group),fill=NA,color='grey',size=0.1)  
  geom_polygon(SHP2,mapping=aes(x=long,y=lat,group=group),fill=NA,color='green',size=0.5)

enter image description here

How could I obtain map from example 2 using the geom_spatvector function used in example 1?

I really would like to use the terra package to read and manipulate shapefiles but then it produces SpatVector class object which is not supperted by the ggplot2 function. This means that only for the plotting purposes I have to transfer it to the older SpatialPolygonsDataFrame and this is exactly what I would like to avoid.

CodePudding user response:

You need to use coord_sf rather than coord_equal. Obviously, we don't have your shapefile, but if I take a similar shapefile of Germany, then we can demonstrate:

library(tidyterra)
library(ggplot2)

p <- ggplot(SHP1)   
  geom_spatvector() 

Firstly, with the standard geom_spatvector plot:

p

enter image description here

Secondly, with axis limits written by a call to geom_sf:

p   coord_sf(ylim = c(47, 52))

enter image description here

  • Related