我想将左图的刻度位置改为右图(刻度在图中)。
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))
我想我可以用grobs获得所需的情节,但我很惊讶没有一个简单的设置来调整滴答位置!
设置axis.ticks.length
给出了几乎正确的解决方案,轴文本也应该更靠近轴。 hjust
无效。
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
答案 0 :(得分:3)
这是一个基于操纵情节凹陷的解决方案。它提供了我正在寻找的东西,但操纵grobs ......永远不是正确的方法(不可读的代码)
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))