Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different tick length on the same axis in ggplot2

Tags:

plot

r

ggplot2

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.

like image 278
Jun Jiang Avatar asked Sep 12 '25 13:09

Jun Jiang


1 Answers

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

like image 127
elielink Avatar answered Sep 15 '25 02:09

elielink