Skip to content

Reduce "object 'geometry' not found" error with geom_sf() #2872

Closed
@yutannihilation

Description

@yutannihilation

Currently, geom_sf() works without specifying geometry aes only when:

  1. the sf object has a geometry column named geometry
  2. the sf object is passed directly to geom_sf(), not via the plot data

I'm afraid it's a bit confusing that the example of nc won't work if we just replace nc with another sf object.

library(ggplot2)

nc <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)
attr(nc, "sf_column")
#> [1] "geometry"

# this works
ggplot(nc) +
  geom_sf(aes(fill = AREA))

nc_gpkg <- sf::st_read(system.file("gpkg/nc.gpkg", package = "sf"), quiet = TRUE)
attr(nc_gpkg, "sf_column")
#> [1] "geom"

# this fails
ggplot(nc_gpkg) +
  geom_sf(aes(fill = AREA))
#> Error in FUN(X[[i]], ...): object 'geometry' not found

Created on 2018-08-29 by the reprex package (v0.2.0).

I want to let ggplot(nc_gpkg) + geom_sf(aes(fill = AREA)) simply work. For example, implementing fortify.sf() seems to solve our problem quickly.

fortify.sf <- function(model, data, ...) {
  if (! "geometry" %in% colnames(model)) {
    model$geometry <- sf::st_geometry(model)
  }
  model
}

But, I'm not fully sure this does the right thing... I feel this is similar kind of problem that we wanted to map grouping variable of grouped_df automatically to group aes, but couldn't (#2378). Are there any smarter way to create mappings automatically?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions