【问题标题】:Change the position of the ticks in ggplot2 (inside the plot) [duplicate]更改 ggplot2 中刻度线的位置(在绘图内)[重复]
【发布时间】:2015-07-23 12:00:35
【问题描述】:

我想将左侧图的刻度位置更改为与右侧相同(刻度在图内)。

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 获得所需的情节,但我很惊讶没有一个简单的设置来调整刻度位置!

编辑(使用解决方案here移动刻度线):

如上所述设置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

【问题讨论】:

标签: r plot ggplot2


【解决方案1】:

这里有一个基于操纵情节的解决方案。它提供了我正在寻找的东西,但操纵 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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2020-12-17
    相关资源
    最近更新 更多