I'm looking for a ggplot2
equivalent for eqscplot
(package MASS
) that can fill the entire plot window while maintaining the scale within a map in a ggplot
.
There is coord_fixed
where cartesian coordinates can be set with fixed ratios (argument aspect =
), but it doesn't work if I'm using geom_sf()
; geom_sf()
requires coord_sf
for a plot to be drawn and can't be a ggplot
layer if coord_sf
is a layer.
There is this answer (ggplot2: Flip axes and maintain aspect ratio of data) but it's not automatic, which is a problem when there are a lot of maps to be made and where automated map making is the ideal workflow. It also doesn't zoom into the points like eqscplot
does.
eqscplot
is able to maintain an aspect ratio when the range
of x
and y
values are widely different, which is helpful for plotting maps.
library(rnaturalearth)
library(rnaturalearthdata)
library(MASS)
library(ggplot2)
world <- ne_countries(scale = 'medium', returnclass = 'sf',
country = c('India', 'Sri Lanka', 'Pakistan', 'Myanmar',
'Malaysia', 'Indonesia', 'Thailand',
'Nepal', 'Bhutan', 'Laos', 'China', 'Iran',
'Maldives'))
RNGkind('Mers')
set.seed(42)
lonlat <- data.frame(lon = rnorm(10, 80, 5),
lat = rnorm(10, 12, 5))
apply(lonlat, 2, range)
lon lat
[1,] 77.17651 9.343545
[2,] 90.09212 14.286645
eqscplot(lonlat$lon, lonlat$lat, type = 'n')
plot(world, add = T, col = NA)
points(lonlat$lon, lonlat$lat, col = 'red', pch = 16)
#Compare the lon/lat ranges on the map with the ranges of the data's longitude and latitude
I was was looking to see if there was a way to do it ggplot2
, but if I don't specify the limits of the longitude and latitude, it takes the extent of the countries I specified in the world
object.
ggplot(data = world) +
geom_sf() +
geom_point(data = lonlat, aes(x = lon, y = lat))
I've got a few hundred maps to make so automating the process with apply
family of functions or for
loops is preferred. But I need something that can automatically zoom into the points that I'm plotting while maintaining the the aspect ratio. I'm looking to do it in ggplot2
because my collaborators aren't as experienced with R
and were taught how to use the tidyverse
, so anything I can do to make the code easier for them to understand can go a long way.
My question is: Is there an eqscplot
equivalent in ggplot2
? Something where the aspect ratio can be set automatically, zooms into where the points are instead of the extent of the world
polygon, and fills the entire plot window while maintaining the scales?