Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Quick hack for a bug with the plot range in ggplot2's stat_density
- require(ggplot2)
- require(proto)
- # Renamed to stat_density2 so as to not interfere with the ggplot2 package
- stat_density2 <- function (mapping = NULL, data = NULL, geom = "area", position = "stack",
- adjust = 1, kernel = "gaussian", trim = FALSE, na.rm = FALSE, ...) {
- StatDensity2$new(mapping = mapping, data = data, geom = geom, position = position,
- adjust = adjust, kernel = kernel, trim = trim, na.rm = na.rm, ...)
- }
- # Also renamed, and added ggplot2::: in front of stat as this is run outside of the package
- StatDensity2 <- proto(ggplot2:::Stat, {
- objname <- "density"
- calculate <- function(., data, scales, adjust=1, kernel="gaussian", trim=FALSE, na.rm = FALSE, ...) {
- data <- remove_missing(data, na.rm, "x", name = "stat_density2",
- finite = TRUE)
- n <- nrow(data)
- if (n < 3) return(data.frame())
- if (is.null(data$weight)) data$weight <- rep(1, n) / n
- range <- scale_dimension(scales$x, c(0, 0))
- xgrid <- seq(range[1], range[2], length=200)
- # The Doc says that the 'trim' parameter works like 'cut' in density. This is not what
- # happens however. As a quick fix I just removed the range here, as this trims the range
- # without respecting the 'trim' parameter.
- dens <- density(data$x, adjust=adjust, kernel=kernel, weight=data$weight) # from=range[1], to=range[2]
- densdf <- as.data.frame(dens[c("x","y")])
- densdf$scaled <- densdf$y / max(densdf$y, na.rm = TRUE)
- if (trim) densdf <- subset(densdf, x > min(data$x, na.rm = TRUE) & x < max(data$x, na.rm = TRUE))
- densdf$count <- densdf$y * n
- rename(densdf, c(y = "density"))
- }
- default_geom <- function(.) GeomArea
- default_aes <- function(.) aes(y = ..density.., fill=NA)
- required_aes <- c("x")
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement