2015-12-14 53 views
7

GGPLOT2可以創建一個非常有吸引力的填充小提琴情節:ggplot2小提琴情節:只填滿中央95%?

ggplot() + geom_violin(data=data.frame(x=1, y=rnorm(10^5)), 
    aes(x=x, y=y), fill='gray90', color='black') + 
    theme_classic() 

我想填充限制分配如果可能的中央95%,剩下的外形完整無缺。有沒有人有如何完成這一建議?

回答

6

這是做你想做的嗎?它需要一些數據處理和兩把小提琴的繪製。

set.seed(1) 
dat <- data.frame(x=1, y=rnorm(10^5)) 

#calculate for each point if it's central or not 
dat_q <- quantile(dat$y, probs=c(0.025,0.975)) 
dat$central <- dat$y>dat_q[1] & dat$y < dat_q[2] 

#plot; one'95' violin and one 'all'-violin with transparent fill. 
p1 <- ggplot(data=dat, aes(x=x,y=y)) + 
    geom_violin(data=dat[dat$central,], color="transparent",fill="gray90")+ 
    geom_violin(color="black",fill="transparent")+ 

    theme_classic() 

enter image description here

編輯:圓邊困擾着我,所以這裏是第二種方法。如果我這樣做,我會想要直線。所以我做了一些演奏與密度(這是小提琴地塊是基於)

d_y <- density(dat$y) 

right_side <- data.frame(x=d_y$y, y=d_y$x) #note flip of x and y, prevents coord_flip later 
right_side$central <- right_side$y > dat_q[1]&right_side$y < dat_q[2] 

#add the 'left side', this entails reversing the order of the data for 
#path and polygon 
#and making x negative 
left_side <- right_side[nrow(right_side):1,] 
left_side$x <- 0 - left_side$x 

density_dat <- rbind(right_side,left_side) 


p2 <- ggplot(density_dat, aes(x=x,y=y)) + 
    geom_polygon(data=density_dat[density_dat$central,],fill="red")+ 
    geom_path() 


p2 

enter image description here

+0

啊,剛纔打我! – Axeman

+1

@Axeman偉大的思想相似嗎?我已經添加了第二種方法。 – Heroka

+0

@賀岡,這太棒了!按照你的猜測,我自己偶然發現了你的第一個方法,但並不滿意。你的第二種方法正是我想要的。非常感謝! – dewarrn1

2

只是做一個選擇第一。概念證明:

df1 <- data.frame(x=1, y=rnorm(10^5)) 
df2 <- subset(df1, y > quantile(df1$y, 0.025) & y < quantile(df1$y, 0.975)) 

ggplot(mapping = aes(x = x, y = y)) + 
    geom_violin(data = df1, aes(fill = '100%'), color = NA) + 
    geom_violin(data = df2, aes(fill = '95%'), color = 'black') + 
    theme_classic() + 
    scale_fill_grey(name = 'level') 

enter image description here