How to scale x axis and add ticks in R
The problem is that xlim(0, 155)
is actually a shorthand for scale_x_continuous(lim = c(0, 155))
. Therefore, when you use both, xlim()
and scale_x_continuous()
, ggplot is confused and will only use one of the two calls of scale_x_continuous()
. If I do this, I get the following warning:
Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.
As you can see, ggplot is only using the scale that you defined last.
The solution is to put the limits and the breaks into one call of scale_x_continuous()
. The following is an example that you can run to see how it works:
data <- data.frame(a = rnorm(1000, mean = 100, sd = 40))
ggplot(data, aes(x = a)) + geom_histogram() +
scale_x_continuous(breaks = seq(0, 155, 5), lim = c(0, 155))
Let me add another remark: The breaks do now not fit well with the bin width, which I find rather odd. So I would suggest that you also change the bin width. The following plots the histogram again, but sets the bin width to 5:
ggplot(data, aes(x = a)) + geom_histogram(binwidth = 5) +
scale_x_continuous(breaks = seq(0, 155, 5), lim = c(0, 155))
The following link provides a lot of additional information and examples on how to change axes in ggplot: http://www.cookbook-r.com/Graphs/Axes_%28ggplot2%29/