boxplot

时间:2016-10-13 05:34:39

标签: r ggplot2 boxplot

我们说我有以下数据框:

library(ggplot2)

set.seed(101)
n=10
df<- data.frame(delta=rep(rep(c(0.1,0.2,0.3),each=3),n), metric=rep(rep(c('P','R','C'),3),n),value=rnorm(9*n, 0.0, 1.0))

我的目标是通过多种因素制作一个箱线图:

p<- ggplot(data = df, aes(x = factor(delta), y = value)) + 
geom_boxplot(aes(fill=factor(metric)))

输出结果为:

enter image description here

到目前为止一切顺利,但如果我这样做:

p+ geom_point(aes(color = factor(metric))) 

我明白了:

enter image description here

我不知道它在做什么。我的目标是在完成here时对异常值进行着色。请注意,this solution会将框的内部颜色更改为白色,并将边框设置为不同的颜色。我希望保持相同颜色的盒子,同时让异常值继承这些颜色。我想知道如何使异常值从各自的箱形图中获得相同的颜色。

2 个答案:

答案 0 :(得分:3)

你想改变异常值的颜色吗?如果是这样,您可以通过两次绘制箱图来轻松完成。

p <- ggplot(data = df, aes(x = factor(delta), y = value)) + 
  geom_boxplot(aes(colour=factor(metric))) +
  geom_boxplot(aes(fill=factor(metric)),  outlier.colour = NA)
                                        # outlier.shape = 21  # if you want a boarder

enter image description here

[EDITED]
colss <- c(P="firebrick3",R="skyblue", C="mediumseagreen")
p + scale_colour_manual(values = colss) +   # outliers colours
    scale_fill_manual(values = colss)       # boxes colours

 # the development version (2.1.0.9001)'s geom_boxplot() has an argument outlier.fill,
 # so I guess under code would return the similar output in the near future.
p2 <- ggplot(data = df, aes(x = factor(delta), y = value)) + 
  geom_boxplot(aes(fill=factor(metric)),  outlier.shape = 21, outlier.colour = NA)

答案 1 :(得分:0)

也许这个:

ggplot(data = df, aes(x = as.factor(delta), y = value,fill=as.factor(metric))) + 
  geom_boxplot(outlier.size = 1)+ geom_point(pch = 21,position=position_jitterdodge(jitter.width=0))

enter image description here