2014-07-16 50 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