2014-03-18 2 views
4

내 플롯에는 전설과 텍스트 주석이 있습니다. 범례를 들어, I는ggplot2 R 위치에 주석을 붙이십시오.

legend.justification=c(1,0), legend.position=c(1,0)

이 플로팅 영역의 위치를 ​​찾기 위해 지정 (예컨대 topright, bottomleft). 내가 주석 층 (http://docs.ggplot2.org/0.9.3.1/annotate.html)을 넣어 그러나, 내가 단지

대신 플롯 영역의 위치의 annotate("text", x = 8e-7, y = 1e-5, label=data.note, size = 5)

가 (필자는 텍스트를 넣을 텍스트의 좌표를 지정할 수 있다는 것 하단 모서리 모서리). 텍스트의 길이 (label)는 다른 플롯에 따라 다를 수 있습니다. 이것을 달성 할 수있는 방법이 있습니까? 감사!

답변

3

이게 네가 원하는거야?

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=...와 실험을 조금있을 것입니다.

4

-InfInf은 왼쪽 아래 모서리에 배치하기 위해 위치 배율의 극단에 매핑하지 않고 사용할 수 있습니다. 참조 점을 텍스트의 왼쪽 하단 모서리로 만들려면 hjustvjust이 필요합니다. [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") 

enter image description here

4

은 "Inf를"해결책은 문제가 당신이 여러 줄의 텍스트를 할 때. 또한 텍스트와 패널 가장자리 사이에는 여백이 없으므로 추한 것입니다. 다른 솔루션은 좋지 않은 데이터에 대해 명시 적으로 언급해야합니다.

원하는 효과는 annotation_custom (또는 내 예에서는 proto 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)