2017-11-26 24 views
1

ggplot2에서면 집합 밀도 그림의 가장 높은 (후부) 밀도 간격을 나타내는 가로선을 그릴 때는 어떻게합니까? 이것은 내가 시도 것입니다 : 내가 패 시팅을 존중하기를 원하는 반면geom_density에서 그리기 간격

# Functions to calculate lower and upper part of HPD. 
hpd_lower = function(x) coda::HPDinterval(as.mcmc(x))[1] 
hpd_upper = function(x) coda::HPDinterval(as.mcmc(x))[2] 

# Data: two groups with different means 
df = data.frame(value=c(rnorm(500), rnorm(500, mean=5)), group=rep(c('A', 'B'), each=500)) 

# Plot it 
ggplot(df, aes(x=value)) + 
    geom_density() + 
    facet_wrap(~group) + 
    geom_segment(aes(x=hpd_lower(value), xend=hpd_upper(value), y=0, yend=0), size=3) 

enter image description here

당신이 볼 수 있듯이, geom_segment 두 측면에 대한 모든 데이터를 계산합니다. 또한 HPDinterval은 패싯 당 한 번만 실행되는 솔루션을 원합니다.

답변

1

hpd 간격을 미리 계산하십시오. ggplot은 데이터가 그룹화 된 경우에도 전체 데이터 프레임에서 aes() 함수의 계산을 평가합니다.

# Plot it 
library(dplyr) 
df_hpd <- group_by(df, group) %>% summarize(x=hpd_lower(value), xend=hpd_upper(value)) 

ggplot(df, aes(x=value)) + 
    geom_density() + 
    facet_wrap(~group) + 
    geom_segment(data = df_hpd, aes(x=x, xend=xend, y=0, yend=0), size=3) 

enter image description here