Search code examples
rggplot2scale

ggplot function for integer breaks (old so solution not working)


library(tidyverse)
df <- tibble(col1 = c("A", "B"), col2 = c(0.4, 0.7))
#> # A tibble: 2 x 2
#>   col1   col2
#>   <chr> <dbl>
#> 1 A       0.4
#> 2 B       0.7

ggplot(df, aes(col1, col2)) + geom_col()

A ggplot of the data frame above looks like this, with breaks that include decimal numbers.

integer 1

There are multiple methods for specifying integer breaks from this stackoverflow question. None of them seem to do what I want. I want there to be two breaks, one at 0 and the other at 1. How do I modify one of these functions below to accomplish that?

# Attempt 1 
ggplot(df, aes(col1, col2)) + 
  geom_col() + 
  scale_y_continuous(
    breaks = function(x) unique(floor(pretty(seq(0, (max(x) + 1) * 1.1)))))

# Attempt 2
ggplot(df, aes(col1, col2)) + 
  geom_col() + 
  scale_y_continuous(breaks = scales::pretty_breaks(2))

# Attempt 3
ggplot(df, aes(col1, col2)) + 
  geom_col() + 
  scale_y_continuous(breaks = c(0, 1))

# Attempt 4
ggplot(df, aes(col1, col2)) + 
  geom_col() + 
  scale_y_continuous(
    breaks = function(x) seq(ceiling(x[1]), floor(x[2]), by = 1))

# Attempt 5
ggplot(df, aes(col1, col2)) + 
  geom_col() + 
  scale_y_continuous(
    breaks = 
      function(x, n = 5)  pretty(x, n)[round(pretty(x, n),1) %% 1 == 0])

Most of the attempts above produce the plot below. None produce what I want. Notice the break for 1 is missing.

integer 2


Solution

  • That's because your y-axis is not going far enough to see the break at 1, it's actually there, you just don't see it :) Simply adjusting the y-axis limits should fix it.

    Here's a simple solution:

    ggplot(df, aes(col1, col2)) + 
      geom_col() + 
      scale_y_continuous(breaks = c(0, 1), limits = c(0, 1))
    

    enter image description here