2014-01-31 2 views
3

검정색의 2 차 곡선과 수평선 색상을 표시하는 범례 (안내선)가있는 다양한 색상의 다양한 레벨의 수평선을 작성하고 싶습니다. 나는 그것을 이해할 수 없다 - 나는 감각이있는 것처럼 보이는 몇 가지 변형을 시도했지만, 전설이 나타나게 할 수는 없다.보조 변수가있는 색상에 대한 ggplot 범례

여기 내 최신 시도의 :

library(ggplot2) 
theme_set(theme_bw()) ## cosmetic 
hdat <- data.frame(harvest_rate=c(5,15,25,30)) 
r <- 1; K <- 100 
ggplot(hdat)+ 
    geom_hline(data=hdat,aes(yintercept=harvest_rate, 
       colour=factor(harvest_rate)))+ 
    stat_function(fun=function(x) r*x*(1-x/K),colour="black")+ 
    expand_limits(x=c(0,110)) 

enter image description here

의 선 밖으로 OK 온,하지만 전설/가이드는 없다.

나는이 대신 할 경우 다음 놀랍게도 수평 라인이 전혀 그려되지 않습니다

ggplot(hdat,aes(yintercept=harvest_rate, 
       colour=factor(harvest_rate)))+ 
    geom_hline()+ 
    stat_function(fun=function(x) r*x*(1-x/K),colour="black")+ 
    expand_limits(x=c(0,110)) 

! 나는 또한 시도했다

중 하나를 그런 식으로 표시되지 않습니다, xy 변수

d <- data.frame(x=0:110) 
d <- transform(d,y=r*x*(1-x/K)) 
ggplot(d,aes(x,y))+geom_line()+ 
     geom_hline(data=hdat,aes(yintercept=harvest_rate, 
       colour=factor(harvest_rate)))+ 
     scale_colour_brewer(palette="Set1") 

가이드를 데이터 프레임을 설정 (나는이 길을 시작했다).

처음 ggplotcolour=NA을 설정하면 범례가 나타나지만 곡선이 사라집니다.

ggplot(d,aes(x,y,colour=factor(1)))+geom_line()+ 
     geom_hline(data=hdat,aes(yintercept=harvest_rate, 
       colour=factor(harvest_rate)))+ 
     scale_colour_brewer(palette="Set1") 

을 다음과 같이 내가 colour=factor(1)를 설정하면 나는 곡선과 전설을 얻을 수 있지만, 곡선은 가짜 색상입니다. geom_line(colour="black")으로 설정을 변경하면 범례가 다시 사라집니다.

(1) 작동하는 해킹과 (2) 누락 된 논리에 대한 설명에 대해 매우 감사하게 생각합니다!

+4

시도'show_guide = TRUE '당신의 geom_hline 층에서은 (아마도 종종 있으므로 전설에 포함되지 않은, 주석으로 사용) – baptiste

+0

OK, documentation-reading fail ... 답장으로 쓰는 것이 좋습니다! –

+0

@baptiste 답을 요구 하시려면, 제가 삭제하겠습니다. – Jaap

답변

3

완전한 답 :

library(ggplot2) 
theme_set(theme_bw()) ## cosmetic 
hdat <- data.frame(harvest_rate=c(5,15,25,30)) 
r <- 1; K <- 100 

ggplot(hdat)+ 
    geom_hline(aes(yintercept=harvest_rate, colour=factor(harvest_rate)), show_guide=TRUE)+ 
    stat_function(fun=function(x) r*x*(1-x/K),colour="black")+ 
    expand_limits(x=c(0,110)) + 
    labs(colour = "Harvest rate") # making a pretty legend title 

결과 :

enter image description here

관련 문제