Skip to content

Error: unable to find an inherited method for function ‘extent’ for signature ‘x = "ggplot2::ggplot"’ #38

@achubaty

Description

@achubaty

Trying to render the plotting vignette, specifically the Plot(ggQbj) line in:

if (requireNamespace("ggplot2")) {
ggObj <- data.frame(x = stats::rnorm(1e3)) |>
ggplot2::ggplot(ggplot2::aes(x = x)) +
ggplot2::geom_histogram()
clearPlot()
Plot(caribou, axes = "L", new = TRUE)
Plot(ggObj)

I'm hitting the extent error in .makeViewports because of hasMethod("extent", is(obj)[1]):

quickPlot/R/plotting-helpers.R

Lines 2292 to 2299 in 99bfafa

# if the object has an extent method
if (hasMethod("extent", is(obj)[1]) && !is.list(obj)) {
# list has an extent method, but too general
out <- extent(obj)
} else {
# for non spatial objects
out <- list(xmin = 0, xmax = 2, ymin = 0, ymax = 2)
}

this is likely the correct thing to check, but there is a ggplot method:

> showMethods("extent")
Function: extent (package quickPlot)
x="ANY"
x="ggplot2::ggplot"
    (inherited from: x="ANY")

this suggests that the actual problem is the incorrect use of methods here: a single 'ANY' method is defined that checks the signature of the object inside the method, rather than defining methods for each allowed signature and letting R deal with method dispatch:

quickPlot/R/plotting-helpers.R

Lines 2795 to 2826 in 99bfafa

setMethod(
"extent",
signature("ANY"),
definition = function(x, ...) {
.ExtentToList(x)
}
)
.ExtentToList <- function(x) {
if (!is(x, "list")) {
x <- if (inherits(x, "sf")) {
x <- as.list(sf::st_bbox(x))
} else { # if (isGridded(x) || inherits(x, "Spatial") || isSpat(x) ||
# is(x, "SpatExtent") || is(x, "Extent")) {
if (!is(x, "SpatExtent")) {
if (isSpat(x) || isSpatial(x))
x <- terra::ext(x)
else {
if (!requireNamespace("raster", quietly = TRUE)) {
stop("Need to install.packages('raster')")
}
x <- raster::extent(x)
}
}
list(
xmin = terra::xmin(x), xmax = terra::xmax(x),
ymin = terra::ymin(x), ymax = terra::ymax(x)
)
}
}
x
}

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