2014-07-16 57 views
2

我有一些奇怪的行爲小提琴劇情,當數據是(部分)恆定小提琴情節以不變的數據?

如果我檢查常量數據並且人爲添加一些小錯誤(例如,通過添加runif(N, min = -0.001, max = 0.001),腳本將運行,但是,這會將其他小提琴圖扭曲到垂直線(參見1),而它應該是這個樣子2


問:

是否有可能(當小提琴劇情部分數據是不變的),以

  • 顯示相應常量數據的簡單水平線
  • 顯示其他小提琴圖,就好像常數不存在一樣?


R代碼裏面:

library(ggplot2) 
library(grid) 
library(gridExtra) 

N <- 20 

test_data <- data.frame(
    idx <- c(1:N, 1:N), 
    vals <- c(runif(N, 0, 1), 
      rep( 0.5, N)),           # <- R script won't run 
      #rep(0.5, N) + runif(N, min = -0.001, max = 0.001)), # <- delivers graphic (distorted) 
    type <- c(rep("range", N), 
      rep("const", N)) 
) 

grid.arrange(
    ggplot(test_data, aes(x = idx, y = vals)) + 
    geom_line(aes(colour = type)), 
    ggplot(test_data, aes(x = type, y = vals)) + 
    geom_violin(aes(fill = type), 
       position = position_dodge(width = 1)) 
) 

distorted violin plots

the 'other' violin plot

+0

答案爲[這個問題](http://stackoverflow.com/questions/24129772/ggplot2-geom-violin-wit h-0-variance)給出了這個問題的一些選擇。如果方差大於0,您可以爲組變量添加一個變量到數據集中,然後在'ggplot'中將數據集進行子集化。使用'dplyr'添加此變量:'test_data = test_data%>%group_by(type)%> %mutate(vars = var(vals))'。 – aosmith

回答

1

我最終得到一些基團(S),其具有零方差小提琴圖(標準偏差)

  • 以顯示0-方差團的扁平線
  • 顯示正常小提琴地塊爲其他組

working violin plot with 0-variance group(s) enter image description here

在我的例子我有3組數據 - 2無零方差和第三個是不變的。 雖然累積的組中,我計算標準偏差(方差將是相同的功能)

library(ggplot2) 
library(gridExtra) 

N <- 20 

test_data <- data.frame() 

# random data from range 
for(grp_id in 1:2) 
{ 
    group_data <- data.frame(
     idx = 1:N, 
     vals = runif(N, grp_id, grp_id + 1), 
     type = paste("range", grp_id) 
    ) 
    group_data$sd_group <- sd(group_data$vals) 
    test_data = rbind(test_data, group_data) 
} 

# constant data 
group_data = data.frame(
    idx = 1:N, 
    vals = rep(0.5, N), 
    type = "const" 
) 
group_data$sd_group <- sd(group_data$vals) 

所建議予加少許偏移,以獲得小提琴情節爲組「const的」

# add a little jittering to get the flat line 
if(0 == group_data$sd_group[1]) 
{ 
    group_data$vals[1] = group_data$vals[1] + 0.00001 
} 
test_data = rbind(test_data, group_data) 

只有現在剩下要做的事情是所有小提琴圖擴展到相同的寬度

grid.arrange(
    ggplot(test_data, aes(x = idx)) + 
     geom_line(aes(y = vals, colour = type)), 
    ggplot(test_data, aes(x = type, y = vals, fill = type)) + 
     geom_violin(scale = "width"), 
    ncol = 1 
) 
+0

在使用子集並保持手動同步顏色後,我設法簡化了我的解決方案'geom_violin(scale =「width」)' – hardmooth