在我的图中,我既有图例又有文字注释。对于图例,我可以指定
legend.justification=c(1,0), legend.position=c(1,0)
定位相对于绘图区域的位置(例如右上角、左下角)。但是,当我放置注释层(http://docs.ggplot2.org/0.9.3.1/annotate.html)时,似乎只能指定文本的坐标
annotate("text", x = 8e-7, y = 1e-5, label=data.note, size = 5)
而不是绘图区域的位置(我想把文本放在左下角)。文本的长度(label
)可能因绘图不同而不同。有没有办法做到这一点?谢谢!
发布于 2014-03-19 03:22:30
这就是你要找的吗??
set.seed(1)
df <- data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df, aes(x,y)) +geom_point()+
annotate("text",x=min(df$x),y=min(df$y),hjust=.2,label="Text annotation")
可能需要对hjust=...
进行一些实验,才能在左下角获得它。
发布于 2014-03-19 06:16:00
您可以利用这样一个事实,即-Inf
和Inf
将映射到位置比例的极端,而无需扩展它们以将其放置在左下角。要使参考点位于文本的左下角,需要使用hjust
和vjust
。使用jlhoward的模拟数据。
set.seed(1)
df <- data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df, aes(x,y)) +geom_point()+
annotate("text",x=-Inf,y=-Inf,hjust=0,vjust=0,label="Text annotation")
发布于 2014-03-19 16:36:43
当你想要多行文本时,"Inf“解决方案有问题。此外,在文本和面板边缘之间没有边距,这是丑陋的。另一种解决方案需要明确提及数据,这也不是很好。
使用annotation_custom (或者在我的示例中,直接使用proto Geom )可以很好地实现所需的效果。您具有可配置的边距、文本和框对齐方式。在下面的代码中增加的好处是,您可以使用类似facets=data.frame(cat1='blue', cat2='tall')
的内容来指定要注释的facet。
library("ggplot2")
annotate_textp <- function(label, x, y, facets=NULL, hjust=0, vjust=0, color='black', alpha=NA,
family=thm$text$family, size=thm$text$size, fontface=1, lineheight=1.0,
box_just=ifelse(c(x,y)<0.5,0,1), margin=unit(size/2, 'pt'), thm=theme_get()) {
x <- scales::squish_infinite(x)
y <- scales::squish_infinite(y)
data <- if (is.null(facets)) data.frame(x=NA) else data.frame(x=NA, facets)
tg <- grid::textGrob(
label, x=0, y=0, hjust=hjust, vjust=vjust,
gp=grid::gpar(col=alpha(color, alpha), fontsize=size, fontfamily=family, fontface=fontface, lineheight=lineheight)
)
ts <- grid::unit.c(grid::grobWidth(tg), grid::grobHeight(tg))
vp <- grid::viewport(x=x, y=y, width=ts[1], height=ts[2], just=box_just)
tg <- grid::editGrob(tg, x=ts[1]*hjust, y=ts[2]*vjust, vp=vp)
inner <- grid::grobTree(tg, vp=grid::viewport(width=unit(1, 'npc')-margin*2, height=unit(1, 'npc')-margin*2))
layer(
data = NULL,
stat = StatIdentity,
position = PositionIdentity,
geom = GeomCustomAnn,
inherit.aes = TRUE,
params = list(
grob=grid::grobTree(inner),
xmin=-Inf,
xmax=Inf,
ymin=-Inf,
ymax=Inf
)
)
}
qplot(1:10,1:10) + annotate_text2('some long text\nx = 1', x=0.5, y=0.5, hjust=1)
https://stackoverflow.com/questions/22488563
复制相似问题