Search code examples
rggplot2histogramx-axis

Histogram using scale_x_continuous() to start from 0


I'm trying to create a histogram with tick marks at each bar. However, when I use scale_x_continuous(), the x-axis adjusted to the lowest number, which happens to be not 0. How can I make the x-axis start from 0? I tried x_lim(0,20) but it got over-ruled by scale_x_continuous().

set.seed(1234)

dat <- as_tibble(sample(20, 100, replace = TRUE)) %>% 
  filter(value > 5)

ggplot(dat, aes(value)) +
  geom_histogram(color = "white", fill = "dark grey", binwidth = 1, boundary = -0.5) +
  scale_x_continuous(breaks = seq(0, 20, 1))

Solution

  • It's xlim(0,20) not x_lim(0,20)

    library(tidyverse)
    
    set.seed(1234)
    
    dat <- as_tibble(sample(20, 100, replace = TRUE)) %>% 
      filter(value > 5)
    
    
    ggplot(dat, aes(value)) +
      geom_histogram(color = "white", fill = "dark grey", binwidth = 1, boundary = -0.5) +
      scale_x_continuous(breaks = seq(0, 20, 1)) +
      xlim(0,20)
    

    ggplot2`