2014-04-20 3 views
2

컨텍스트 : R/ggplot2.ggplot2에 플롯 내 범례 레이블을 붙이는 방법

전설 요소를 여기에있는 에너지 (Co, 4,6,10, ...)와 같이 플롯 내부에 넣는 자동화 된 방법 (또는 수동 방법)이 있습니까? 줄거리 옆에있는 상자?

Source: Radiation Oncology Physics: A Handbook for Teachers and Students, EB. Podgorsak

출처 : 방사선 종양학 물리학 : 교사와 학생, EB를위한 핸드북. Podgorsak

+0

가되면 비슷한 질문 : [여기] (http://stackoverflow.com/questions/21868353를/drawing-labels-on-flat-of-contour-lines-in-ggplot2)을 사용합니다. – tonytonov

+0

'directlabels' 패키지가 조금 도움이 될 수도 있습니다 – baptiste

답변

3

이렇게 가까운 것 같습니다. 나는 "반자동"로이 특징 것 :이 필요 확실히 일부 조정은, 그러나 대부분의 작업이 당신을 위해 이루어집니다 ...

이 까다로운 비트는 텍스트 레이블을 배치되지 않은 (geom_text(...)를), 플롯 된 커브에 중단을 작성합니다. 이것은 geom_rect(...)으로 이루어지며, 여기서 사각형의 폭은 strwidth(...)을 사용하여 결정된 최대 레이블 폭으로 설정됩니다.

# create sample data 
df <- data.frame(x=rep(seq(0,20,.01),5),k=rep(1:5,each=2001)) 
df$y <- with(df,x*exp(-x/k)) 

library(ggplot2) 
eps.x <- max(strwidth(df$k)) # maximum width of legend label 
eps.y <- eps.x*diff(range(df$y))/diff(range(df$x)) 
ggplot(df,aes(x,y))+ 
    geom_line(aes(group=factor(k)))+ 
    geom_rect(data=df[df$x==5,], 
      aes(xmax=x+eps.x, xmin=x-eps.x, ymax=y+eps.y, ymin=y-eps.y), 
      fill="white", colour=NA)+ 
    geom_text(data=df[df$x==5,],aes(x,y,label=k))+ 
    theme_bw() 

너무 라인 색상을 원하는 경우 :

ggplot(df,aes(x,y))+ 
    geom_line(aes(color=factor(k)))+ 
    geom_rect(data=df[df$x==5,], 
      aes(xmax=x+eps.x, xmin=x-eps.x, ymax=y+eps.y, ymin=y-eps.y), 
      fill="white", colour=NA)+ 
    geom_text(data=df[df$x==5,],aes(x,y,label=k), colour="black")+ 
    scale_color_discrete(guide="none")+ 
    theme_bw() 
+0

당신은 아티스트입니다. 고맙습니다! – Zet

+0

'eps.y <- eps.x * diff (range (df $ y))/diff (range (df $ x))'행이 무엇을하는지 이해할 수 없습니다. 이것이 어떻게 작동할까요? 왜 그냥 strheight()라고 부르지 않니? –

관련 문제