Increase breaks in discrete legend

Viewed 240

I'm currently getting started learning R and I'm focusing on data visualisation.

For this plot, I'm displaying the count of overlapping dots on the map using geom_count which gives me the following graph

geom_count graph with only 2 legend elements

As you can see the legend only contains two elements, namely the size of the dot when 5 data points are overlapping, and the size of it when 10 data points are overlapping. How can I increase the breaks that the legend includes? I have been trying with to use discrete_x_scale in order to increase the number of breaks but I just get lost and can't manage it.

The code for my current graph is simply this

ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) + 
  geom_count()

I would also like to know how to change the filling color of the dot according to the number of overlapping data points.

2 Answers

You need to modify scale_size, not scale_x:

ggplot(data = mpg, mapping = aes(x = cty, y = hwy)) +
    geom_count() +
    scale_size(breaks = c(2, 4, 6, 8))

To also change the fill colour, you can use a computed aesthetic:

ggplot(data = mpg, mapping = aes(x = cty, y = hwy, color = after_stat(n))) +
    geom_count() +
    scale_size(breaks = seq(0, 15, 3)) +
    scale_color_continuous(breaks = seq(0, 15, 3)) +
    guides(size = guide_legend(), color = guide_legend())

Note the guides call: without that, you’d get two separate legends for the size and colour below each other, rather than one merged legend.

To address the question of changing the fill colour as well as size try by creating an explicit count variable which is used to control size and colour:

library(dplyr)
library(ggplot2)

mpg1 <- 
  mpg %>% 
  group_by(cty, hwy) %>% 
  summarise(count = n())

 
ggplot(data = mpg1, mapping = aes(x = cty, y = hwy, colour = count, size = count))+
  geom_point() +
  scale_size_continuous(breaks = seq(2, 14, by = 2))+
  scale_colour_continuous(breaks = seq(2, 14, by = 2))+
  guides(colour = guide_legend(), size = guide_legend())

Note to ensure that only one legend title appears both the breaks for size and colour need to be identical.

Created on 2021-04-01 by the reprex package (v1.0.0)

Related