1

When using geom_histogram() to plot histogram, the plot will always not start at zero as expect. See my example below:

set.seed(20) 
randomnum <- rnorm(40) 
data <- data.frame(number = randomnum[randomnum > 0]) 
ggplot(data, aes(x = number)) +  
  geom_histogram(color="black", fill="grey40")

enter image description here

Even the data do not contain negative number, the histgram will start at a negative value. The code below may see more clear:

ggplot(data, aes(x = number)) +
  geom_histogram(color="black", fill="grey40", binwidth = 0.1) +
  scale_x_continuous(breaks = c(0, seq(0, 2, 0.1)))

enter image description here

The histgram will start at -0.1, but the original data do not contain the negative data.
My ideal plot is the x axis will start at 0, and every plot bar share the same width. The plot may be like this:

enter image description here

There are some simmilar questions in stackoverflow, link1 and link2. They change the parameter in scale_x_continuous(). But it only changes the axis scales and labels and do not solve my problem.

Leon Smith
  • 97
  • 6
  • 1
    This answer https://stackoverflow.com/a/46453008/680068 from your links should answer this question, too? – zx8754 Jun 16 '21 at 08:09

1 Answers1

1

OK, the solution is:

ggplot(data, aes(x = number)) +
  geom_histogram(color="black", fill="grey40", binwidth = 0.1, 
                 boundary = 0, closed = "left") +
  scale_x_continuous(breaks = c(0, seq(0, 2, 0.1)))

The boundary is the key parameter!

Leon Smith
  • 97
  • 6