Skip to content

Instantly share code, notes, and snippets.

@sfischme
Created September 14, 2011 21:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfischme/1217836 to your computer and use it in GitHub Desktop.
Save sfischme/1217836 to your computer and use it in GitHub Desktop.
PositionHeap for ggplot2
library(ggplot2)
df <- data.frame(a=sample(1:500,1000,replace=T),b=1)
PositionHeap <- proto(Position, {
adjust <- function(., data, scales) {
if (empty(data)) return(data.frame())
check_required_aesthetics(c("x", "y"), names(data), "position_stacking")
if (is.null(.$height)) .$height <- resolution(data$x) * 0.4
if (is.null(.$width)) .$width <- resolution(data$y) * 0.4
data$offset.y <- 0
data$offset.x <- 0
dups <- (1:nrow(data))[duplicated(data)]
cat(system.time(for (i in dups) {
ddups <- (data$x==data$x[i]) & (data$y==data$y[i])
ddups[1:i] <- FALSE
data$offset.y[ddups] <- data$offset.y[ddups]+.$height
data$offset.x[ddups] <- data$offset.x[ddups]+.$width
}))
data$y <- data$y+data$offset.y
data$x <- data$x+data$offset.x
return(data)
}
objname <- "stacking"
desc <- "stacking points to avoid overplotting"
examples <- function(.) {
qplot(am, vs, data=mtcars)
# Default amount of jittering will generally be too much for
# small datasets:
qplot(am, vs, data=mtcars, position="stacking")
# Control the amount as follows
qplot(am, vs, data=mtcars, position=position_stacking(w=0.0, h=0.1))
qplot(am, vs, data=mtcars, position=position_stacking(w=0.1, h=0.0))
}
})
position_stacking <- PositionHeap$build_accessor()
ggplot(df,aes(x=a,y=b,)) + geom_point(,position=position_stacking(w=0.0,h=1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment