Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 geom_count set legend breaks to integers

I want to use the geom_count graph from ggplot2 but with a too small range in values the legend breaks become floating points for counts of occurances e.g. 1 1.5 2 2.5 3

Here is a test case:

test = mtcars[1:6,]

ggplot(test, aes(cyl, carb)) +
  geom_count(aes(color = ..n.., size = ..n..)) +
  guides(color = 'legend')

How can I make the breaks occur only at full integers?

like image 462
voiDnyx Avatar asked Jan 29 '23 17:01

voiDnyx


1 Answers

You can set the breaks for the continuous color and size scales.

You can give a vector of values for the breaks, but per the documentation the breaks argument can also be given:

a function that takes the limits as input and returns breaks as output

So for a simple case like your example, you could use as.integer or round as the function.

ggplot(test, aes(cyl, carb)) +
     geom_count(aes(color = ..n.., size = ..n..)) +
     guides(color = 'legend') +
     scale_color_continuous(breaks = round) +
     scale_size_continuous(breaks = round)

For a larger range of integers than your example, you could either manually enter the breaks, e.g., breaks = 1:3, or write a function that takes the limits of the scale and returns a sequence of integers. You could then use this function for breaks.

That could look like:

set_breaks = function(limits) {
     seq(limits[1], limits[2], by = 1)
}

ggplot(test, aes(cyl, carb)) +
     geom_count(aes(color = ..n.., size = ..n..)) +
     guides(color = 'legend') +
     scale_color_continuous(breaks = set_breaks) +
     scale_size_continuous(breaks = set_breaks)
like image 155
aosmith Avatar answered Feb 01 '23 07:02

aosmith