Last active
January 15, 2020 20:08
-
-
Save sharlagelfand/de996e40d2f919a961f10343a45eb862 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
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
Is diamonds intended to be a subclass of ggplot?