I build an Histogram in R using geom_histogram, I want to scale my x axis up to 155 insted of 252 that is showing and to see a tick evrey 5 numbers (0,5,10 etc), I used the scale_x_continuous(breaks=(0,155,5)
. it worked but the histogram is not presented all across the screen.
I used xlim(0,155)
it showed the histogram all across the screen but it override the ticks I defined.

- 15,166
- 6
- 57
- 71

- 119
- 1
- 1
- 6
2 Answers
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/

- 15,166
- 6
- 57
- 71
-
I use one set of breaks for my raw_data plot but later on want to compare that side by side with a FFT reconstruction changing the scale of the raw_data plot to match that of the FFT reconstruction. I'm doing this in markdown. I assumed that the last scale_x_continuous would be used. It works, but how to suppress the message? – Nate Lockwood Jul 13 '18 at 20:40
-
@NateLockwood Comments are not really the place to discuss new questions. If you have a question and cannot find an answer on StackOverflow, you better ask a new question. That said, try to enwrap the command, where you replace the scale, by `suppressMessages()`. – Stibu Jul 14 '18 at 07:15
break
takes a list of sequence for your major tick. Try:
scale_x_continuous(breaks=seq(0,155,5))

- 2,293
- 1
- 15
- 13
-
This sets the tick marks as requested, but does not set the upper limit of the x axis to 155. – Stibu Jan 16 '15 at 18:42
-