I'm trying to come up with a way of plotting a ternary heatmap using R. I think ggtern should be able todo the trick, but I don't know how to do a binning function like stat_bin in vanilla ggplot2. Here's What I have so far:
require(ggplot2)
require(ggtern)
require(MASS)
require(scales)
palette <- c( "#FF9933", "#002C54", "#3375B2", "#CCDDEC", "#BFBFBF", "#000000")
sig <- matrix(c(1,2,3,4),2,2)
data <- data.frame(mvrnorm(n=10000, rep(2, 2), Sigma))
data$X1 <- data$X1/max(data$X1)
data$X2 <- data$X2/max(data$X2)
data$X1[which(data$X1<0)] <- runif(length(data$X1[which(data$X1<0)]))
data$X2[which(data$X2<0)] <- runif(length(data$X2[which(data$X2<0)]))
## Print 2d heatmap
ggplot(data, aes(x=X1, y=X2)) +
stat_bin2d(bins=50) +
scale_fill_gradient2(low=palette[4], mid=palette[3], high=palette[2]) +
xlab("Percentage x") +
ylab("Percentage y") +
scale_y_continuous(labels = percent) +
scale_x_continuous(labels = percent) +
theme_bw() + theme(text = element_text(size = 15))
data$X3 <- with(data, 1-X1-X2)
data <- data[data$X3 >= 0,]
## Print ternary heatmap
ggtern(data, aes(x=X1, y=X2, z=X3)) +
geom_point(color="black",size=1,shape=16) + theme_bw()
The first call to ggplot produces a nice 2d heatmap:
The second plot plots the points in the ternary coordinate system. I need something like stat_bin2d to get the count of points in each triangle. Ideally I want to set the size of the triangles like I do in 2d by setting the bins variable of stat_bin2d.
OK, so after playing around with this for a while I figured out a way to do this. Would love to hear from you if there's a smart way to do this.
The code is below, here's the plot I produced with it: