rggplot2histogramintervalsbins

How to set specific intervals in histogram plots in R?


I want to plot a histogram with a binwidth of 4. I am not able to fix the intervals of these data. I want my bins to start from x = 28 and have intervals of 4 from there on. For ex - 28-32, 32-36, 36-40 and so on. How do I set specific intervals and fix a start value for the histograms?

crushing_strength <- c(40,37.9,29,31.7,39.3,40.7,42.7,40,50.3,
                                  33.8,39.3,42.1,45.5,41.4,47.6,38.6,35.9,
                                  41.4,44.1,40,40.7,42.1,38.6,36.5,40.7)
test_no <- seq(1:25)

data_example <- data.frame(test_no,crushing_strength)


ggplot(data_example, aes(x = crushing_strength))+
  geom_histogram(binwidth=4)+
  scale_x_continuous()

Solution

  • You can specify your desired breaks via the breaks= argument of geom_histogram:

    library(ggplot2)
    
    ggplot(data_example, aes(x = crushing_strength)) +
      geom_histogram(breaks = seq(28, 52, 4)) +
      scale_x_continuous()
    

    enter image description here