【问题标题】:"Unitless", qualitative, or relative axis scales ggplot2“无单位”、定性或相对轴刻度 ggplot2
【发布时间】:2016-12-02 05:27:33
【问题描述】:

假设我有以下图表

dat <- data.frame(x = 1:10, y = 1:10)

ggplot(dat, aes(x=x, y=y)) + geom_point()

但我实际上对任一轴上的值 2.5, 5, 7.5, 10 并不感兴趣。我只想标记“从低到高”之类的东西。我知道我可以标记+ xlab("Low to High"),但我希望“低”位于轴的最左侧(在原点下方),而“高”位于最右侧(在10.0 下方),可能有一个箭头来自低--->高。我可以手动指定休息时间,但这似乎太过分了。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这样的事情可能会有所帮助,

    dat <- data.frame(x = 1:10, y = 1:10)
    
    p <- ggplot(dat, aes(x=x, y=y)) + geom_point() +
      scale_x_continuous('', breaks=NULL)+
      scale_y_continuous('', breaks=NULL)
    
    g <- ggplotGrob(p)
    library(gtable)
    library(grid)
    
    my_axis <- function(low="low", high="high", axis=c("x", "y"), ...){
    
      axis <- match.arg(axis)
    
      if(axis == "x"){
      g1 <- textGrob(low, x=unit(0,"npc"), hjust=0)
      g3 <- textGrob(high, x=unit(1,"npc"), hjust=1)
      g2 <- segmentsGrob(grobWidth(g1) + unit(2,"mm"), unit(0.5,"npc"),
                   unit(1,"npc") - grobWidth(g3)- unit(2,"mm"), 
                   unit(0.5,"npc"), ...)
    
      } else if(axis == "y"){
        g1 <- textGrob(low, y=unit(0,"npc"), rot=90, hjust=0)
        g3 <- textGrob(high, y=unit(1,"npc"), rot=90, hjust=1)
        g2 <- segmentsGrob(unit(0.5,"npc"),grobHeight(g1) + unit(2,"mm"), 
                           unit(0.5,"npc"),
                           unit(1,"npc") - grobHeight(g3)- unit(2,"mm"), 
                           ...)
    
      }
    
      grobTree(g1,g2,g3)
    }
    
    g <- gtable_add_grob(g, my_axis(arrow=arrow(length=unit(2,"mm"))), 
                         t=nrow(g)-2, b=nrow(g)-1, l=4)
    g <- gtable_add_grob(g, my_axis(axis="y", arrow=arrow(length=unit(2,"mm"))), 
                         t=3, l=1,r=3)
    grid.newpage()
    grid.draw(g)
    

    【讨论】:

    • +1,但我必须在textGrob 中手动指定水平位置。我更喜欢 dat 值的更改不需要其他更改的解决方案。
    • 这些位置实际上是“npc”单位,也就是“标准化父坐标”,也就是你想要的,我想。
    • @baptiste :这似乎被打破了。
    【解决方案2】:

    作为替代方案,由于您确实要求“低 ---> 高”,因此这里有一个不涉及拆解情节的选项

    dat <- data.frame(x = 1:10, y = 1:10)
    low_to_high <- paste0("low   ", paste0(rep("-", 35), collapse = ""), ">   high")
    
    library(ggplot2)
    ggplot(dat, aes(x, y)) + 
      geom_point() +
      labs(x = low_to_high, y = low_to_high) +
      coord_equal() +
      theme_bw() +
      theme(axis.title = element_text(size=20), 
            axis.text = element_blank(),
            axis.ticks = element_blank())
    

    诚然,所需的- 的数量会有所不同,需要根据您的绘图大小进行调整,而且它不如正确渲染的箭头漂亮。不过,从头开始制作起来很快。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      • 2023-01-28
      相关资源
      最近更新 更多