Skip to content

Instantly share code, notes, and snippets.

@dsparks
Created March 25, 2011 11:04
Show Gist options
  • Save dsparks/886694 to your computer and use it in GitHub Desktop.
Save dsparks/886694 to your computer and use it in GitHub Desktop.
Artificially-colored overlapping densities.
require(ggplot2)
Data <- data.frame(Group = sample(c(1, 2), 100, replace = T))
Data$Value <- rnorm(100, Data$Group * 2 - 6, 1)
Data$Group <- LETTERS[1:2][Data$Group]
Plot1 <- qplot(Value, data = Data, geom = "density", fill = Group, alpha = I(1/2))
Plot1 <- Plot1 + scale_fill_manual(values = c("#3E6995", "#953E3E"))
print(Plot1)
MatteDensities <- function(values, groups, colA = hsv(7/12, 7/12, 7/12), colB = hsv(0, 7/12, 7/12)){
ColorPalette <<- colorRampPalette(c(colA, colB))(3)
Range <- extendrange(values)
Split <- split(values, groups)
names(Split) <- c("A", "B")
densA <- density(Split$A, n = 1000, from = Range[1], to = Range[2], na.rm = T)
densB <- density(Split$B, n = 1000, from = Range[1], to = Range[2], na.rm = T)
overlap <- apply(cbind(densA$y, densB$y), 1, min)
plot <- qplot(densA$x, densA$y, geom = "area", fill = I(ColorPalette[1]))
plot <- plot + geom_area(aes(x = densB$x, y = densB$y), fill = I(ColorPalette[3]))
plot <- plot + geom_area(aes(x = densB$x, y = overlap), fill = I(ColorPalette[2]))
return(plot)
}
TestPlot <- MatteDensities(values = Data$Value, groups = Data$Group, colA = hsv(7/12, 7/12, 7/12), colB = hsv(0, 7/12, 7/12))
print(TestPlot)
TestPlot <- MatteDensities(values = Data$Value, groups = Data$Group, colA = gray(4/5), colB = gray(0))
print(TestPlot)
TestPlot <- MatteDensities(values = Data$Value, groups = Data$Group, colA = hsv(0, 0, 7/12), colB = hsv(0, 7/12, 7/12))
print(TestPlot)
TestPlot <- MatteDensities(values = Data$Value, groups = Data$Group, colA = hsv(0, 7/12, 0), colB = hsv(0, 7/12, 7/12))
print(TestPlot)
TestPlot <- MatteDensities(values = Data$Value, groups = Data$Group, colA = hsv(7/12, 7/12, 0), colB = hsv(7/12, 7/12, 11/12))
print(TestPlot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment