R小提琴图和箱形图一起使填充表现出不同的箱形图

时间:2018-03-23 13:57:11

标签: r ggplot2 reshape2 melt

好的,所以我想将小提琴情节与 white 箱图一起绘制,但我的数据有点棘手。我将data.frame中的数据与多个列融合,每个列的值都对应于两个级别的因子,这里是我数据的近似值:

library(ggplot2)
library(reshape2)

dat <- list(
  A = rbind(
    data.frame(group = "1",
               vals = rnorm(500)),
    data.frame(group = "2",
               vals = rnorm(100))
  ),
  B = rbind(
    data.frame(group = "1",
               vals = rnorm(500)),
    data.frame(group = "2",
               vals = rnorm(100))
  ),
  C = rbind(
    data.frame(group = "1",
               vals = rnorm(500)),
    data.frame(group = "2",
               vals = rnorm(100))
  )
)

dat.melt <- melt(dat)

我能找到的最好的是手动设置填充,但它会影响小提琴图和箱形图:

dodge <- position_dodge(width = 1)

p <- ggplot(dat.melt, aes(x = L1, y = value, fill = group))+
  geom_violin(position = dodge)+
  geom_boxplot(width = 0.3,
                 position = dodge,
                 outlier.shape = NA)+
  scale_fill_manual(values=c("white", "white"))

Said plot

我可以只制作白色的箱形图而不是小提琴吗?

P.S。我怎样才能为小提琴制作传说而不显示箱形图?

2 个答案:

答案 0 :(得分:4)

试试这个:

p <- ggplot(dat.melt, aes(x = L1, y = value)) +
  geom_violin(aes(fill = group), position = dodge) +
  geom_boxplot(aes(group=interaction(group,L1)), 
            width=0.3, fill="white", position=dodge,
            outlier.shape=NA)
print(p)

enter image description here

答案 1 :(得分:1)

你也可以试试这个:

ggplot(dat.melt, aes(x = L1, y = value, fill=group))+
  geom_violin(position = position_dodge(width = 1)) +
  geom_boxplot(data = dat.melt, 
               aes(x = L1, y = value, col=group), fill="white", 
               position = position_dodge(width = 1), width=0.3,outlier.shape=NA)+
  geom_boxplot(position = position_dodge(width = 1), alpha=0, width=0.3)

enter image description here