在ggplot2中创建一个小提琴图,其中小提琴和箱线图颜色不同。

3
我正在尝试创建一个分组小提琴图(见下图),其中我为四个分类变量绘制了3个级别。除了箱子与宽的小提琴图的颜色相同使得难以查看之外,该图表的数据显示正常。理想情况下,我希望所有的箱子都保持白色。我知道箱子改变颜色的原因是我选择了fill参数。我想知道是否有一种方法可以将geom_violingeom_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


ggplot(aes()) 中删除 fill = variable 并将其放置在 geom_boxplot(aes()) 中。在这种情况下,只有箱线图会受到 fill 参数的影响。 - bVa
1个回答

3

一切取决于您在哪里编写fill

  • ggplot(aes())内部:所有新层都将受到影响。
  • geom_boxplot(aes())内部:只有此层会受到影响。

特别是如果您想稍后使用scale_fill_manual(),则将其编写在aes中非常重要。

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接