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))
jay.sf
  • 60,139
  • 8
  • 53
  • 110
Tim
  • 81
  • 6
  • 1
    Use the "limits = " option in the `scale_x_continuous()` call – Dave2e Apr 29 '22 at 14:51
  • add ` scale_x_continuous(limits = c(0, 20))` – jpsmith Apr 29 '22 at 14:54
  • 1
    @Dave2e I think it's better to use `coord_cartesian`. This uses all the data to construct summaries and then "zooms" the plot. `scale_x_continuous` , `xlim` and `ylim` (and similar) first *filters* the data and then constructs statistics, which can lead to misleading (or simply incorrect) summaries. So `coord_cartesian` has the behaviour that I believe most users would "expect". See [here](https://stackoverflow.com/questions/67266325/fill-area-between-axis-and-plot-fill-area-ggplot2) for another example. – Limey Apr 29 '22 at 15:03

1 Answers1

2

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`