r - "Unitless",定性或相对轴刻度ggplot2

标签 r ggplot2

假设我有以下图表

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 下方),可能带有来自低 ---> 高的箭头。我可以手动指定休息时间,但这似乎太麻烦了。

最佳答案

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

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)

enter image description here

关于r - "Unitless",定性或相对轴刻度ggplot2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26267942/

相关文章:

r - 控制ggplot2中facet_grid/facet_wrap的顺序?

r - ggplot2 在 pdf、R 中嵌入所有使用的字体

r:重叠赋值

r - ggplot2:y 轴标签在绘图区域内左对齐

r - 使用子集时添加图例

r - 表达式()中的换行符?

r - ggplot2 中 fiddle 图的中位数和四分位数

javascript - r - 如何在 shinyapp 中自动滚动到 div 的底部?

r - levelplot - 如何使用它,有什么简单的例子吗?

r - FELM + Stargazer - 将工具变量估计与 OLS 对齐