我想将左侧图的刻度位置更改为右侧图(刻度在图内)。
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))
Run Code Online (Sandbox Code Playgroud)
我想我可以用 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
Run Code Online (Sandbox Code Playgroud)
这里有一个基于操纵图块的解决方案。它给出了我正在寻找的东西,但操纵 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))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5775 次 |
最近记录: |