How to change the colour of bins in ggplot (geom_bin2d) to reflect difference between density in that area and the average density across a dataset?

Viewed 3590

Say I have some data that looks a bit like this

library(ggplot2)
library(dplyr)

employee <- employee <- c('John','Dave','Paul','Ringo','George','Tom','Jim','Harry','Jamie','Adrian')
quality <- c('good', 'bad')
x = runif(4000,0,100)
y = runif(4000,0,100)
employ.data <- data.frame(employee, quality, x, y)

And I'm working with a geom_bin2d plot that looks like this

ggplot(dat, aes(x, y)) +
  geom_bin2d(binwidth = c(20, 20)) +
  scale_fill_gradient2(low="darkred", high = "darkgreen")

plot

How can I change the colour of the bins to reflect the percentage of the x/y points that are 'bad' compared to the overall average in that area across the dataset? I.e, if the average of 'bad' points in the bottom left bin is x number, and the average for John in that area is y lower number, how can I make the bin colour darker to show that his count is lower?

I figured this could work to create the averages:

df2 <-  employ.data
df2$xbin <- cut(df2$x, breaks = seq(0, 100, by = 20))
df2$ybin <- cut(df2$y, breaks = seq(0, 100, by = 20))
df2 <- df2 %>% group_by(xbin, ybin) %>% mutate(ave_pct = mean(quality == "bad"))
df2 <- df2 %>% group_by(employee, xbin, ybin) %>%  mutate(person_pct = mean(quality == "bad"))

But then I have no idea how to plot that.

1 Answers

So if I am understanding you correctly, you would like to have the bins colored by how each respective bins percentage of bad employees compares to the overall percentage of bad employees. To accomplish this, I changed up how this was calculated to this:

df <- employ.data %>%
  mutate(xbin = cut(x, breaks = seq(0, 100, by = 20)),
         ybin = cut(y, breaks = seq(0, 100, by = 20)),
         overall_ave = mean(quality == "bad")) %>%
  group_by(xbin, ybin) %>%
  mutate(bin_ave = mean(quality == "bad")) %>%
  ungroup() %>%
  mutate(bin_quality = bin_ave - overall_ave)

This creates the bins, then finds the overall percentage of "bad" quality employees. Then it groups by the respective bins, and finds the percentage of "bad" employees per bin. Then it compares each bin average to the overall average. This gives a positive value for bin_quality for bins with a higher percentage of "good" employees and a negative number for bins with a higher percentage of "bad" employees.

You can then graph it by adding a fill = bin_quality and group = bin_quality argument to your aes() call inside of ggplot. You also need to add aes(group = bin_quality) to your geom_bin2d call. It looks like this:

ggplot(df, aes(x, y, fill = bin_quality, group = bin_quality)) +
  geom_bin2d(aes(group = bin_quality), binwidth = c(20, 20)) +
  scale_fill_gradient2(low="darkred", high = "darkgreen") 

This gives you this graph:

enter image description here

Related