0
votes

When you plot a bar chart in ggplot2, the y axis labelling automatically stops at the break below the highest value. In the graph the last label is 40, whereas I want it to round up to the next break which would be 50.

 set.seed (52)
 date<-data.frame(date=sample(seq(as.Date('2020-01-01'), as.Date('2020-01-31'), by="day"),1000,replace=TRUE))
 ggplot(data=date)+
 geom_bar(mapping=aes(x=date))

enter image description here

I know adding +scale_y_continuous(limits=c(0,50)) will manually make the graph at 50 but I would need to keep changing this bit of the code. Is there a way to do this dynamically within the ggplot function?

1
Try adding scale_y_continuous(breaks = scales::pretty_breaks(15)) in the final part of your code!Duck

1 Answers

0
votes

One option could be defining a sequence function for breaks like this:

#Function
f <- function(y) seq(floor(min(y)), ceiling(max(y)),by=10)
#Code
set.seed (52)
date<-data.frame(date=sample(seq(as.Date('2020-01-01'), as.Date('2020-01-31'), by="day"),1000,replace=TRUE))
ggplot(data=date)+
  geom_bar(mapping=aes(x=date))+
  scale_y_continuous(breaks = f)

Output:

enter image description here

Another option could be playing with the max values from your variable and use the function round_any() from plyr:

library(plyr)
library(ggplot2)
#Code
set.seed (52)
date<-data.frame(date=sample(seq(as.Date('2020-01-01'), as.Date('2020-01-31'), by="day"),1000,replace=TRUE))
#Extract limits
upper <- round_any(max(table(date$date)),10,f=ceiling)
#Plot
ggplot(data=date)+
  geom_bar(mapping=aes(x=date))+
  scale_y_continuous(limits = c(0,upper))

Output:

enter image description here