I have a set of 2D points with category labels, and want to visualize which category dominates each cell of a grid super-imposed over the 2D plane.
I imagined I would be able to use stat_summary_2d with a function that selects the most frequent value as shown below, but I got different plots for three variations that should be identical except for the legend labels.
Am I misusing stat_summary_2d? Is there a better way to generate this plot?
library(ggplot2)
set.seed(12345)
x = runif(1000)
y = runif(1000)
lab = rep(c("red", "blue", "green", "yellow"), 250)
df = data.frame(x=x, y=y, lab=factor(lab, labels=c("red", "blue", "green", "yellow")))
df$val = as.numeric(df$lab)
#Attempt 1
ggplot(df, aes(x=x, y=y)) +
stat_summary_2d(aes(z=lab),
fun=function(z) names(which.max(table(z))),
binwidth=.1)
#Attempt 2
ggplot(df, aes(x=x, y=y)) +
stat_summary_2d(aes(z=val),
fun=function(z) names(which.max(table(z))),
binwidth=.1)
#Attempt 3
ggplot(df, aes(x=x, y=y)) +
stat_summary_2d(aes(z=as.numeric(lab)),
fun=function(z) names(which.max(table(z))),
binwidth=.1)