MCur
MCur

Reputation: 13

Can you add a count to the legend for each level of a factor in ggplot?

I am producing a scatterplot using ggplot, and will be colouring the data points by a given factor. The legend that is produced, details the colour assigned to each level of the factor, but is it possible for it to also count the number of points in each factor.

For example, I have included the code for the cars data set:

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(aes(colour = factor(cyl)))

In this plot, I would be looking to have the count for each number of cylinders. So 4(Count 1), 6(Count 2) and 8(Count 3).

Thanks in advance.

Upvotes: 1

Views: 1107

Answers (1)

dww
dww

Reputation: 31452

you can try something like this

mtcars %>%
  group_by(cyl) %>%
  mutate(label = paste0(cyl, ' (Count ', n(), ')'))  %>%
  ggplot(aes(wt, mpg)) + 
    geom_point(aes(colour = factor(label)))

Upvotes: 3

Related Questions