在ggplot2

时间:2016-04-26 05:00:12

标签: r ggplot2 violin-plot

我正在尝试创建一个分组的小提琴图(见图),我正在为四个分类变量绘制3个级别。除了箱子与后面更宽的小提琴曲线相同的颜色使得它们难以观看的事实之外,情节也很好。理想情况下,我希望所有的盒子始终保持白色。我明白盒子改变颜色的原因是我选择的fill。我想知道是否有办法将geom_violin的填充与geom_boxplot分开。

以下是我正在使用的精简代码

p <- ggplot(df, aes(x=metric, y=value, fill=variable))+
geom_violin(width=0.9, position=position_dodge(0.75), bw=1.5)+
geom_boxplot(width=0.3, outlier.shape = NA, position=position_dodge(0.75))+
scale_fill_manual(values=c("gray50", "gray75", "gray100"),
                breaks=c("res.error.random", "res.error.increase", "res.error.decrease"),
                labels=c("random cost", "overestimated", "underestimated"))

Example of the plot I am creating

1 个答案:

答案 0 :(得分:1)

所有取决于你写fill的地方:

  • ggplot(aes())内:所有新图层都会受到关注。
  • geom_boxplot(aes())内:只关注此层。

aes内写一下这一点非常重要,特别是如果您想稍后使用scale_fill_manual()

以下是生成数据的完整答案:

df <- data.frame(var1 = sample(c("A", "B", "C"), 50, replace =T),
             var2 = sample(c("group1", "group2", "group3"), 50, replace =T),
             value = sample(c(1,2,3,4,5,6,7,8,9,10), 50, replace =T))

1. boxplotviolin [ggplot(aes(fill =))]的相应颜色:

ggplot(df, aes(x=var1, y=value, fill = var2, group = interaction(var1,var2))) +
geom_violin(width=0.9, position=position_dodge(0.75), bw=1.5) +
geom_boxplot(width=0.3, outlier.shape = NA, position=position_dodge(0.75))

enter image description here

2.不同的颜色[geom_violin(aes(fill =))]:

ggplot(df, aes(x=var1, y=value, group = interaction(var1,var2)))+
geom_violin(width=0.9, position=position_dodge(0.75), bw=1.5, aes(fill = var2))+
geom_boxplot(width=0.3, outlier.shape = NA, position=position_dodge(0.75), fill = "white")

enter image description here