Skip to content

Instantly share code, notes, and snippets.

@sharlagelfand
Last active January 15, 2020 20:08
Show Gist options
  • Save sharlagelfand/de996e40d2f919a961f10343a45eb862 to your computer and use it in GitHub Desktop.
Save sharlagelfand/de996e40d2f919a961f10343a45eb862 to your computer and use it in GitHub Desktop.
library(ggplot2)
plot_diamonds <- function() {
p <- ggplot(head(diamonds), aes(x = cut, y = price)) +
geom_jitter()
res <- list(
name = "diamonds",
p = p
)
class(res) <- "diamonds"
res
}
print.diamonds <- function(x) {
print(x[["p"]])
invisible(x)
}
my_p <- plot_diamonds()
# Prints ggplot2 plot
my_p
# But $name is available too!
my_p$name
#> [1] "diamonds"
# If I try to add additional ggplot2 stuff...
# Doesn't work
my_p +
ggtitle("Diamonds")
#> Error in my_p + ggtitle("Diamonds"): non-numeric argument to binary operator
# Works
my_p[["p"]] +
ggtitle("Diamonds")
@ryanbthomas
Copy link

Is diamonds intended to be a subclass of ggplot?

@ryanbthomas
Copy link

You might need to redefine the + function so that for a diamonds object you call the + function on the ggplot part and keep the other stuff

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment