如何根据第三个变量的类别/值更改ggplot2箱形图中抖动点的颜色?

时间:2015-11-29 18:42:47

标签: r ggplot2

我想改变用ggplot2创建的框图中抖动点的颜色

    library(ggplot2) 

# create factors with value labels 
mtcars$gear <- factor(mtcars$gear,levels=c(3,4,5),
                      labels=c("3gears","4gears","5gears")) 
mtcars$am <- factor(mtcars$am,levels=c(0,1),
                    labels=c("Automatic","Manual")) 
mtcars$cyl <- factor(mtcars$cyl,levels=c(4,6,8),
                     labels=c("4cyl","6cyl","8cyl")) 

p <- ggplot(mtcars, aes(x=gear, y=mpg)) + 
  geom_boxplot()
p + geom_jitter(shape=16, position=position_jitter(0.2), alpha=.3, colour="red")

将“red”替换为类别(或连续变量的值)。 例如以下内容无效,因为“手动”类别不是颜色。

p + geom_jitter(shape=16, position=position_jitter(0.2), alpha=.3, colour=mtcars$am) 

1 个答案:

答案 0 :(得分:3)

您需要在aes内使用另一个geom_jitter,如下所示:

p + geom_jitter(shape=16, position=position_jitter(0.2), alpha=.3, aes(colour=am))

结果是:

enter image description here