Home > Software design >  Is there a way to add legend and count to each level for geom_point?
Is there a way to add legend and count to each level for geom_point?

Time:01-13

enter image description here

Is there a way to add a legend with the count to give density of each row?

Or an easier way to show it?

Thanks very much!

Couldn't even get a legend added :)

Code I used:

data %>% 
  ggplot(aes(x = subscribed, y = campaign))  
  geom_point ()  
  geom_jitter() 

CodePudding user response:

You could per group (subscribed) create a label which is calculated beforehand the number of n() observations and assign these as a column string. This can be used in the aes to make sure it is shown in the legend. Here is a reproducible example:

library(dplyr)
library(ggplot2)
df %>%
  group_by(subscribed) %>%
  mutate(count = paste0(subscribed, ' (n = ', n(), ')')) %>%
  ggplot(aes(subscribed, campaign, colour = factor(count)))   
  geom_jitter()

Created on 2023-01-12 with reprex v2.0.2


Created data:

df <- data.frame(campaign = runif(100),
                 subscribed = rep(c("no", "yes"), 50))
  • Related