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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With