在ggplot2中使用NPC坐标的annotation_custom

5

我想在每个面板底部绘制一个框,每个面板可能具有不同的y范围。该框应始终从x轴的3到7,并从面板底部的边界到大约5%的y轴高度之间。因此,我想以单位指定例如annotation_customgeom_rect的坐标:

xmin=unit(3, "native"), xmax=unit(7,"native"), ymin=unit(0,"npc"), ymax=unit(0.05,"npc")

我能做到,但似乎单位被忽略了,总是使用本地单位。

library("grid")
library("ggplot2")

df <- data.frame(x=c(1:10,1:10),y=c(1:10,1001:1010),condition=rep(c("A","B"),each=10))
g <- rectGrob(gp=gpar(fill="black"))
p <- ggplot(df, aes(x=x,y=y)) + geom_line() + facet_wrap(~ condition, scales="free_y") 
p + geom_rect(xmin=3,xmax=7,ymin=0.56,ymax=1,colour="black", fill="black")

g <- rectGrob(gp=gpar(fill="black"))
p + annotation_custom(g, xmin=3, xmax=7, ymin=0, ymax=1 )
p + annotation_custom(g, xmin=unit(3, "native"), xmax=unit(7,"native"),ymin=unit(0,"npc"),ymax=unit(1,"npc") )
1个回答

7

您可以做以下事情:

g <- rectGrob(y=0,height = unit(0.05, "npc"), vjust=0, 
              gp=gpar(fill="black"))
p + annotation_custom(g, xmin=3, xmax=7, ymin=-Inf, ymax=Inf)

enter image description here


不知怎么的,这个问题让我想到了如何定义“复杂”单位,“1 npc + 2i cm”,其中实部(虚部)表示相对(绝对)单位。 - baptiste

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接