"无单位",定性或相对轴标度ggplot2

时间:2014-10-08 23:18:24

标签: 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实际上并不感兴趣。我想要标记的就是&#34;从低到高&#34;。我知道我可以标记+ xlab("Low to High"),但我更喜欢&#34; Low&#34;位于轴的最左侧(原点下方)和&#34;高位&#34;在最右边(10.0下面),可能是一个来自Low的箭头---&gt;高。我可以手动指定休息时间,但这似乎太多了。

2 个答案:

答案 0 :(得分:9)

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

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

答案 1 :(得分:0)

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

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())

enter image description here

不可否认,所需-的数量会有所不同,需要根据您的地块大小进行调整,而且不如正确渲染的箭头那么漂亮。不过,这很快就可以从头开始。