Problem with plotting a polygon with ggplot + osmdata

230 Views Asked by At

I have a problem working with plotting a polygon obtained by osmdata. First, I get the polygon of the object using this code

library(osmdata)
loespejo_mersal <- opq_osm_id (type = "way", id = 39259197)%>%
opq_string () %>%
osmdata_sf ()

And i got the data without problem, but when I need to plot in a certain limit, I got the error.

ggplot() +
  geom_sf(data = loespejo_mersal$osm_polygons,
          inherit.aes = FALSE,
          fill = "red",
          size = .1,
          alpha = .5)+
  coord_sf(xlim= c(-70.71, -70.67),
           ylim = c(-33.54, -33.50),
           expand = FALSE)+
  labs(title = "TEST Mersan")

Warning message:
In st_cast.GEOMETRYCOLLECTION(X[[i]], ...) :
  only first part of geometrycollection is retained

But if i change the limits, I don't have problems.

ggplot() +
  geom_sf(data = loespejo_mersal$osm_polygons,
          inherit.aes = FALSE,
          fill = "red",
          size = .1,
          alpha = .5)+
  coord_sf(xlim= c(-70.75, -70.65),
           ylim = c(-33.6, -33.5),
           expand = FALSE)+
  labs(title = "TEST Mersan")

I'm trying to understand the error, but I'm stuck :(

1

There are 1 best solutions below

0
On

That's because xlim, ylim doesn't cover the whole bounding box of your polygon. To check it we will use sf library:

library(osmdata)
library(ggplot2)
library(sf)

loespejo_mersal <- opq_osm_id (type = "way", id = 39259197)%>%
  opq_string () %>%
  osmdata_sf ()

lmbbox <- st_bbox(st_as_sf(loespejo_mersal$osm_polygons))
lmbbox
#>      xmin      ymin      xmax      ymax 
#> -70.70874 -33.55168 -70.68260 -33.52892

Let's provide set up xlim, ylim for whole area of bounding box:

ggplot() +
  geom_sf(data = loespejo_mersal$osm_polygons,
          inherit.aes = FALSE,
          fill = "red",
          size = .1,
          alpha = .5)+
  coord_sf(xlim= c(lmbbox[1], lmbbox[3]),
           ylim = c(lmbbox[2], lmbbox[4]),
           expand = FALSE)+
  labs(title = "TEST Mersan")

And just to confirm, it's related to ggplot (and how it treats geometries), we can use simple plot:

plot(loespejo_mersal$osm_polygons$geometry, col="darkgreen")

There was similar question: Error when plotting latitude and longitude points on US map in RStudio. It can be related to projection, because a simple reprojection to EPSG:3857 and ggplotting went smoothly:

b<- st_transform(a, crs = "EPSG:3857")
st_bbox(b)
#>     xmin     ymin     xmax     ymax 
#> -7871261 -3968762 -7868351 -3965722

ggplot() +
  geom_sf(data = b,
          inherit.aes = FALSE,
          fill = "red",
          size = .1,
          alpha = .5) +
  coord_sf(xlim= c(-7871400, -7868000),
         ylim = c(-3967762, -3966722),
         expand = FALSE)+
  labs(title = "TEST Mersan")

Created on 2022-02-03 by the reprex package (v2.0.1)