0
votes

I've seen two great examples on SO where two sets of different ticks were added to the same plot in ggplot2, see Insert blanks into a vector for, e.g., minor tick labels in R and ggplot2 displaying unlabeled tick marks between labeled tick marks. However, what if I want two sets of ticks with different lengths? It's fairly easy to do this in base R (data and code modified from ref 2):

library("magrittr")
library("ggplot2")

set.seed(5)
df <- data.frame(x = rnorm(500, mean = 12.5, sd = 3))

breaks <- seq(2.5, 25, .5)

plot(hist(df$x,breaks = breaks), xaxt = "n", col = "gray66")
axis(1, tck = -.02, at = breaks[breaks %% 2.5 == 0], lwd = 2, lwd.ticks = 2)
axis(1, tck = -.01, lwd = 0, at = breaks[breaks %% 2.5 != 0], labels = NA, lwd.ticks = 1)

and I get (notice the two sets of ticks on X axis with different lengths):

base R plot

I don't see how this is done in ggplot2, the axis.ticks.length arguement in theme() only takes the first element of a vector for plotting when I tried passing a vector of the same length of the breaks.

1
Does this question help? stackoverflow.com/questions/14490071/…Peter
@Peter It's the same as the two examples I mentioned above I think. It use major and minor ticks to skip labels for minor breaks, but it cannot add another set of tick length.Jun Jiang
Check out the documentation in the ggh4x package I think you will find that you can edit the tick mark lengths.Peter
@Peter Thanks! I think this is it!Jun Jiang

1 Answers

0
votes

As Peter mentionned there is a ggh4x package for that:

install.packages('ggh4x')
library(ggh4x)

set.seed(5)
df <- data.frame(x = rnorm(500, mean = 12.5, sd = 3))


    ggplot(df,aes(x=x) )+
      geom_histogram()+
      scale_x_continuous(
        minor_breaks = seq(0, 20, by = 1),
        breaks = seq(0, 20, by = 5), limits = c(0, 20),
        guide = "axis_minor" # this is added to the original code
      )+
      theme(ggh4x.axis.ticks.length.minor = rel(0.5))

It can be used as above. Is this what you were willing for?

enter image description here