Search code examples
rggplot2axis-labels

Standard breaks with limits in ggplot2 axis


What I want is quite simple, yet hard to implement: Set ticks where ggplot2() would set them, and additionally at the limits. Since I am dealing with many datasets, I want to avoid setting the ticks on my own.

require(ggplot2)
ggplot(data=ChickWeight, aes(ChickWeight$Time)) geom_histogram(binwidth=1)

In order to add max(ChickWeight$Time) to the axis, I have tried pretty(), which goes beyond the maximum:

ggplot(data=ChickWeight, aes(ChickWeight$Time)) + geom_histogram(binwidth=1)
 + scale_x_continuous(breaks=pretty(ChickWeight$Time))

...as well as pretty_breaks(), which makes even less breaks:

require(scales)
ggplot(data=ChickWeight, aes(ChickWeight$Time)) + geom_histogram(binwidth=1)
 + scale_x_continuous(breaks=pretty_breaks(ChickWeight$Time))

But none of the solutions takes any argument that looks like maximum. My maximum values are however something special, which is why I want to include it in the plot.


Solution

  • One solution would be to combine pretty() and max() as the breaks= values to set additional tick at maximal value.If function pretty() will produce values larger than maximal value those values will not be shown due to subsetting.

    ggplot(data=ChickWeight, aes(Time)) + geom_histogram(binwidth=1)+ 
      scale_x_continuous(breaks=c(pretty(ChickWeight$Time)[pretty(ChickWeight$Time)<max(ChickWeight$Time)],max(ChickWeight$Time)))
    

    enter image description here