19

I am drawing barchart for discrete data and ggplot by default adjust the y-axis for me, but gives me y-axis label with breaks at 0.5 interval which I don't like it. I tried scale_y_discrete but y-axis breaks is given for every discrete value, which is not good also.

Can I force the y-axis break to be composed of integer only, and give proper breaks for each of the facet?

Sample script is as below:

set.seed(1)
chart.data <- data.frame(x=rep(LETTERS[1:10],3),
                         y=c(sample(0:10,10,replace=TRUE),
                             sample(0:100,10,replace=TRUE),
                             sample(0:1000,10,replace=TRUE)),
                         group=sort(rep(1:3,10)))
chart <- ggplot(data=chart.data,aes(x=x,y=y))
chart <- chart + geom_bar(stat="identity")
chart <- chart + scale_y_discrete()
chart <- chart + facet_wrap(facets=~group,nrow=1,scale="free_y")

Update #1

Since the post is being considered as possible duplicate, the script is refined to show a more complicated scenario.

lokheart
  • 23,743
  • 39
  • 98
  • 169

2 Answers2

27

First, as your y data are continuous you should use scale_y_continuous(). In this function you can add argument breaks= pretty_breaks() (add library scales to use function pretty_breaks()). If you don't provide any number inside pretty_breaks() then in this case you will get integer numbers on y axis. You can set number of breaks to display, for example, pretty_breaks(4) but for the first facet where you have range 0-10 it will still display only integer values and the number of breaks will be larger to get "nice" numbers.

library(scales)
ggplot(data=chart.data,aes(x=x,y=y)) + 
  geom_bar(stat="identity") +  
  facet_wrap(facets=~group,nrow=1,scale="free_y")+
  scale_y_continuous(breaks= pretty_breaks())
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
5

You can also direclty specify the breaks in a function. Below are a few examples of how you could do this. Also look at the breaks argument in ?discrete_scale.

chart + scale_y_discrete(breaks=function(n) c(0, floor(max(n)/2), max(n)))    
chart + scale_y_discrete(breaks=function(n) n[floor(length(n)/5)*1:5+1])
chart + scale_y_discrete(breaks=function(n) 10^(ceiling(log10(max(n)))-1)*2*0:5)
shadow
  • 21,823
  • 4
  • 63
  • 77
  • 1
    Can you explain your solution? After executing your solution, the labels for `y-axis` are missing. – Prradep Oct 20 '17 at 15:01