在ggplot小提琴图中为组着色

时间:2019-02-13 17:36:26

标签: r ggplot2 violin-plot

我是R编程新手。 在绘制ggplot小提琴图时卡住了。 我希望为我的3组提供颜色bluegreenred。 这是我的数据框:

> print(employee_withoutEmployeeID[1:5,])
> 
  EnvironmentSatisfaction JobSatisfaction WorkLifeBalance
1                       3               4               2
2                       3               2               4
3                       2               2               1
4                       4               4               3
5                       4               1               3

我正在尝试的是:

png(file="answer5.png")
answer5 <- ggplot(stack(employee_withoutEmployeeID), aes(x = ind, y= values) )
answer5 + geom_violin()  + scale_fill_manual(values=c("#0000FF", "#00FF00", "#FF0000")) + 
  labs(title="Answer 5", 
       subtitle="",
       caption="Answer 5",
       x="Measure",
       y="Rating")  
dev.off()

我正确绘制了小提琴图,但是没有颜色填充。我不确定如何使用scale_fill_manual 请建议

2 个答案:

答案 0 :(得分:2)

您需要定义要填充的变量。堆栈函数会将ind列添加到您的输入data.frame中,因此我将fill=ind添加到了aes选项中。

answer5 <- ggplot(stack(employee_withoutEmployeeID), aes(x = ind, y= values, fill=ind) )
answer5 + geom_violin()  + scale_fill_manual(values=c("#0000FF", "#00FF00", "#FF0000")) + 
   labs(title="Answer 5", 
        subtitle="",
        caption="Answer 5",
        x="Measure",
        y="Rating")  

enter image description here

答案 1 :(得分:2)

fill需要在geom_violin中指定:

library(ggplot2)
ggplot(iris, aes(x= Species, y = Sepal.Width) ) +
       geom_violin(aes(fill= Species))  + 
       scale_color_manual(values=c("#0000FF", "#00FF00", "#FF0000")) + 
       labs(title="Answer 5", subtitle="",  caption="Answer 5",
         x="Measure", y="Rating")  

enter image description here

相关问题