on-internet
← Community

Color points by density when plotting continuous variable by categorical variable with modern {ggplot2}

Stack Overflow ·

I'm trying to recreate the appearance of a jitter plot where the density of the points is colored. I'm trying to do this with only functions from packages within {tidyverse}. So far, my solution looks like this... measure_density <- function(x, window_width = 0.5) { x %>% mutate(bin = cut(x$value, seq(min(x$value), max(x$value), window_width))) %>% mutate(n = n(), .by = bin) %>% pull(n) } tibble(name = rep(c("A", "B"), each = 10000), value= c(rnorm(10000, 10, 1.9), rnorm(10000, 5, 1.9))) %>% nest(data = -name) %>% mutate(n = map(data, measure_density, window_width = 0.5)) %>% unnest(c(data, n)

Comments

Sign in or sign up to comment and upvote.

No comments yet.