When you import a package, it's "loaded via a namespace (and not attached)" (quoting from sessionInfo()
).
When you want to use a function from an imported package you typically call it using the structure ggplot2::ggplot()
, as you have done.
Therefore, to use autoplot
you would still need to use ggplot2::autoplot()
.
If you don't, your package is not aware of the autoplot
function from ggplot2
.
There are a few solutions to this:
- use
Depends: ggplot2
(see links below for a discussion on Imports
vs Depends
, and section 1.1.3 or writing R extensions]
- define a
plot
method which then calls the various ggplot2::ggplot()
functions
- continue with
autoplot.bigobenchmark
, but require the user to load ggplot2
prior to use (an example of this in practice is in the zoo package. See also ?zoo::autoplot
- Export your own
autoplot
function, but this may cause conflict if the user then later loads ggplot2
Here's an example of solution 2
#' plot for bigobenchmark object
#'
#' @importFrom ggplot2 autoplot
#'
#' @param object
#'
#' @return A ggplot2 plot
#' @export
#'
#' @examples
#' # Create plot for benchmarks
#' library(ggplot2)
#' bench <- bigobenchmark(1:n, for(i in 1:n) for(i in 1:n) 1:n, args=seq(from=1, to=100, length.out = 50))
#' plot(bench)
#'
#' @author Andrew Prokhorenkov
plot.bigobenchmark <- function(object) {
plt <- ggplot2::ggplot(data = object$benchmarks, ggplot2::aes(x=arg, y=mean, colour=expr))
plt <- plt + ggplot2::geom_line()
plt <- plt + ggplot2::geom_pointrange(ggplot2::aes(ymin=min, ymax=max))
plt
}
And here's an example of solution 4
#' Autoplot for bigobenchmark object
#'
#' @importFrom ggplot2 autoplot
#'
#' @param object
#'
#' @return A ggplot2 plot
#' @export
#'
#' @examples
#' # Create plot for benchmarks
#' library(ggplot2)
#' bench <- bigobenchmark(1:n, for(i in 1:n) for(i in 1:n) 1:n, args=seq(from=1, to=100, length.out = 50))
#' autoplot(bench)
#'
#' @author Andrew Prokhorenkov
autoplot <- function(object) UseMethod("autoplot")
#' @export
autoplot.bigobenchmark <- function(object) {
plt <- ggplot2::ggplot(data = object$benchmarks, ggplot2::aes(x=arg, y=mean, colour=expr))
plt <- plt + ggplot2::geom_line()
plt <- plt + ggplot2::geom_pointrange(ggplot2::aes(ymin=min, ymax=max))
plt
}
A better explanation of Imports
vs Depends
is given by Josh O'Brian and majom (quoting Hadley) in this SO answer
export
theautoplot
function to make it available to the user. – Atlante