Change the position of ticks in ggplot2 (inside the plot)

I would like to change the position of the ticks of the left plot as the right one (the ticks are inside the plot).

library(ggplot2)
library(grid)

p <- ggplot(mtcars,aes(mpg,cyl))+
  geom_point() + 
  theme(
        axis.ticks.length=unit(0.5,"cm"),
        axis.line = element_line(color = 'black',size=0.1),
        axis.ticks.y = element_line(size=1,color='red'),
        axis.text.y = element_text(hjust=0.5))

enter image description here

I think I can get the desired plot playing with rodents, but I am surprised that there is no easy setting to adjust the position of the ticks!

change (label change labels using the solution here ):

the setting axis.ticks.length, as mentioned, gives an almost correct solution, the axis text should also be placed closer to the axis. hjustIt does not work.

p <- ggplot(mtcars,aes(mpg,cyl))+
  geom_point() + 
  theme(
    axis.ticks.length=unit(-0.25, "cm"), 
    axis.ticks.margin=unit(0.5, "cm"),
    axis.line = element_line(color = 'black',size=0.1),
    axis.ticks.y = element_line(size=1,color='red'),
    axis.text.y = element_text(hjust=0.5)) ##this don't work

enter image description here

+4
source share
1 answer

It uses a solution based on the manipulation of plot rodents. It gives exactly what I'm looking for, but manipulating grobs ... will never be the right way (unreadable code)

adjust_ticks <- 
  function(pn,adj=0.5){
    ## get grobs 
    p <- p +theme(
      axis.ticks.length=unit(adj,"cm")
    )
    gt <- ggplotGrob(p)
    # Get the row number of the left axis in the layout
    rn <- which(gt$layout$name == "axis-l")
    ## Extract the axis ticks grobs (text)
    axis.grobs <- gt$grobs[[rn]]
    axisb <- axis.grobs$children[[2]]  
    ## change the position of ticks (text and ticks )
    gt$grobs[[rn]]$children[[2]]$grobs[[2]]$x <- axisb$grobs[[2]]$x + unit(adj,"cm")
    gt$grobs[[rn]]$children[[2]]$grobs[[1]]$x <- axisb$grobs[[1]]$x + unit(adj,"cm")
    ## show the differnce 
    gt
  }

plot(adjust_ticks(p))

enter image description here

+3

Source: https://habr.com/ru/post/1599289/


All Articles