Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

r - annotation_custom with npc coordinates in ggplot2

I would like to draw a box at the bottom of each panel, where each panel may have different y-ranges. The box should always be from 3 to 7 on the x-axis and from the border at the bottom of the panel to about 5% of y-axis high. So I would like to specify the coordinates of e.g. annotation_custom or geom_rect in units something like:

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

I can do it, but the units seem to be ignored, its always native.

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") )
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could do,

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...