r - Change the position of the ticks in ggplot2 (inside the plot) -
this question has answer here:
i change position of ticks of left plot right 1 (ticks inside 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))
i think can desired plot playing grobs surprise there not simple setting adjust ticks position!
edit (shift tick marks using solution here):
setting axis.ticks.length
mentioned gives right solution , axis text should postioned more near axis. hjust
has no effect.
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
here solution based on manipulating plot grobs. gives looking manipulating grobs...is never right way go (unreadable code)
adjust_ticks <- function(pn,adj=0.5){ ## grobs p <- p +theme( axis.ticks.length=unit(adj,"cm") ) gt <- ggplotgrob(p) # row number of left axis in layout rn <- which(gt$layout$name == "axis-l") ## extract axis ticks grobs (text) axis.grobs <- gt$grobs[[rn]] axisb <- axis.grobs$children[[2]] ## change position of ticks (text , 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 differnce gt } plot(adjust_ticks(p))
Comments
Post a Comment