Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale x axis and add ticks in R

Tags:

r

ggplot2

axis

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.

like image 904
eliran azulay Avatar asked Jan 16 '15 15:01

eliran azulay


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/

like image 178
Stibu Avatar answered Sep 29 '22 09:09

Stibu


break takes a list of sequence for your major tick. Try:

scale_x_continuous(breaks=seq(0,155,5))
like image 28
Sunhwan Jo Avatar answered Sep 29 '22 09:09

Sunhwan Jo