在我的情节中,我有传说和文本注释.对于传说,我可以指定
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)的长度可能因不同的图而异.有没有办法实现这个目标?谢谢!
你可以使用这个事实,-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")
Run Code Online (Sandbox Code Playgroud)

这是你在找什么?

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")
Run Code Online (Sandbox Code Playgroud)
可能需要进行一些实验hjust=...才能将其精确地放在左下角.
当您需要多行文本时,“Inf”解决方案会出现问题。另外,文字和面板边缘之间没有边距,很难看。另一种解决方案需要明确提及数据,这也不好。
使用annotation_custom(或者在我的示例中,直接使用原始Geom)可以很好地实现所需的效果。您可以配置边距、文本和框对齐方式。以下代码中的额外好处是您可以指定使用诸如 之类的内容来注释哪个方面facets=data.frame(cat1='blue', cat2='tall')。
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8254 次 |
| 最近记录: |