Skip to content

Instantly share code, notes, and snippets.

@daattali
Created May 8, 2015 03:12
Show Gist options
  • Save daattali/38691b4eee641bc63336 to your computer and use it in GitHub Desktop.
Save daattali/38691b4eee641bc63336 to your computer and use it in GitHub Desktop.
S3 method does not show parent params in autocomplete
# There are two humans: `human` and `angry_human`. They only differ in the fact
# that angry humans have a frown on their face.
# Example code:
# dean <- human("Dean")
# ex <- angry_human("Ex")
# plot(dean)
# plot(ex)
# When plotting `dean`, RStudio shows me all the available parameters.
# But when plotting `ex`, RStudio only shows the params of the immediate class,
# but it would be very useful to also see what other params I can use (all
# the params of the parent class)
library(ggplot2)
human <- function(name) {
structure(name, class = "human")
}
angry_human <- function(name) {
structure(name, class = c("angry_human", "human"))
}
plot.human <- function(x, face_col = "black", eye_col = "blue",
mouth_col = "white", background_col = "transparent",
...)
{
face <- circle()
eyes <- rbind(
circle(c(0.4, 0.3), 0.1),
circle(c(-0.4, 0.3), 0.1)
)
mouth <- dplyr::data_frame(x = seq(-0.5, 0.5, length.out = 500),
y = x ^ 2 - 0.6)
ggplot() +
geom_polygon(data = face, aes(x, y), fill = face_col) +
geom_polygon(data = eyes, aes(x, y), fill = eye_col) +
geom_path(data = mouth, aes(x, y), color = mouth_col, size = 2) +
theme(axis.text = element_blank(), axis.title = element_blank(),
line = element_blank(),
panel.background = element_rect(fill = background_col)) +
ggtitle(x)
}
plot.angry_human <- function(x, frown_col = "white", ...) {
res <- NextMethod("plot")
res +
geom_segment(aes(x = -0.6, y = 0.6, xend = -0.2, yend = 0.45),
color = frown_col, size = 1, show_guide = FALSE) +
geom_segment(aes(x = 0.2, y = 0.45, xend = 0.6, yend = 0.6),
color = frown_col, size = 1, show_guide = FALSE)
}
circle <- function(center = c(0, 0), radius = 1, npoints = 500){
t <- seq(0, 2 * pi, length.out = npoints)
x <- center[1] + radius * cos(t)
y <- center[2] + radius * sin(t)
return(data.frame(x = x, y = y))
}
# example
dean <- human("Dean")
ex <- angry_human("Ex")
plot(dean)
plot(ex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment