2013-10-16 109 views
2

這個問題是對這裏提出的問題的答案的延伸:Median and quartile on violin plots in ggplot2ggplot2中高級小提琴圖的中位數和四分位數

溶液工作很漂亮,但如何將它擴展使用選項,例如填充=「富」

實施例時,也採取了小提琴圖的位置考慮在內:

require(ggplot2) 

median.quartile <- function(x){ 
    out <- quantile(x, probs = c(0.25,0.5,0.75)) 
    names(out) <- c("ymin","y","ymax") 
    return(out) 
} 

ggplot(data=mtcars,aes(x=factor(cyl),y=drat, fill=factor(am)))+ 
    geom_violin() + 
    stat_summary(fun.y=median.quartile,geom='point') 

Violin plot with summary

這裏彙總統計變得混雜,因爲它沒有考慮到填充星座映射的位移。

這可以修復嗎?

提前 - 謝謝!

回答

4

您應該將position = position_dodge(width = 0.9)添加到stat_summary()以確保點根據填充值閃避。

ggplot(data=mtcars,aes(x=factor(cyl),y=drat, fill=factor(am)))+ 
    geom_violin() + 
    stat_summary(fun.y=median.quartile,geom='point', 
       position = position_dodge(width = 0.9)) 

enter image description here

+1

你怎麼知道使用0.9? – nstjhp

+0

@nstjhp當兩個組被geom_violin()填充閃避時,它似乎是默認值 - 通過嘗試找到它。 –