programing

R : 다중 레이어 ggplot에 대한 사용자 정의 범례

projobs 2021. 1. 15. 07:30
반응형

R : 다중 레이어 ggplot에 대한 사용자 정의 범례


두 개의 개별 데이터 프레임에서 오는 데이터로 ggplot에 대한 사용자 정의 범례를 얻으려고합니다. 재현 가능한 최소 예는 아래를 참조하세요.

내가 달성하려는 것은 리본 채우기, 검은 색 선 및 빨간색 선을 설명하는 범례를 갖는 것입니다.

require(ggplot2)
x=seq(1,10,length=100)
data=data.frame(x,dnorm(x,mean=6.5,sd=1))
names(data)=c('x','new.data')
x.ribbon=seq(1,10,length=20)
ribbon=data.frame(x.ribbon,
                  dnorm(x.ribbon,mean=5,sd=1)+.01,
                  dnorm(x.ribbon,mean=5,sd=1)-.01,
                  dnorm(x.ribbon,mean=5,sd=1))
names(ribbon)=c('x.ribbon','max','min','avg')
ggplot()+geom_ribbon(data=ribbon,aes(ymin=min,ymax=max,x=x.ribbon),fill='lightgreen')+
  geom_line(data=ribbon,aes(x=x.ribbon,y=avg),color='black')+
  geom_line(data=data,aes(x=x,y=new.data),color='red')+
  xlab('x')+ylab('density')

여기에 이미지 설명 입력


colour을 설정하는 대신 지오메트리 미학 을 사용 하여fill 매핑 한 다음 또는 을 사용하십시오 . aesscale_xxx_manualscale_xxx_identity

ggplot()+geom_ribbon(data=ribbon,aes(ymin=min,ymax=max,x=x.ribbon,fill='lightgreen'))+
    geom_line(data=ribbon,aes(x=x.ribbon,y=avg,color='black'))+
    geom_line(data=data,aes(x=x,y=new.data,color='red'))+
    xlab('x')+ylab('density') + 
    scale_fill_identity(name = 'the fill', guide = 'legend',labels = c('m1')) +
    scale_colour_manual(name = 'the colour', 
         values =c('black'='black','red'='red'), labels = c('c2','c1'))

여기에 이미지 설명 입력

범례를 생성 guide = 'legend'하려면 강제 scale_..._identity지정해야합니다 .

scale_...manual값에 대해 명명 된 벡터를 전달할 수 있습니다. 이름은 호출 내에서 색상을 호출 한 이름이어야하며 geom_...멋지게 레이블을 지정할 수 있습니다.

참조 URL : https://stackoverflow.com/questions/18394391/r-custom-legend-for-multiple-layer-ggplot

반응형