使用ggplot2绘制箱形图的平均值和异常值点

时间:2014-05-17 12:31:13

标签: r ggplot2

我试图使用可用的数据here绘制下面框图的异常值和平均点。数据集有3个不同的因子和1个值列,用于3600行。

当我在代码下方运行时,它显示了平均点,但没有正确绘制异常值

ggplot(df, aes(x=Representations, y=Values, fill=Methods)) +
  geom_boxplot() +
  facet_wrap(~Metrics) +  
  stat_summary(fun.y=mean, colour="black", geom="point", position=position_dodge(width=0.75)) +
  geom_point() +
  theme_bw()

enter image description here

同样,当我修改下面的代码时,平均点消失!!

ggplot(df, aes(x=Representations, y=Values, colour=Methods)) +
  geom_boxplot() +
  facet_wrap(~Metrics) +  
  stat_summary(fun.y=mean, colour="black", geom="point", position=position_dodge(width=0.75)) +
  geom_point() +
  theme_bw()

enter image description here

在这两种情况下,我都收到消息:“ymax未定义:使用y调整位置”而不是“3次。”

任何建议如何修复它?我想在单个箱形图中绘制平均点,并显示与图形颜色相同的异常值。

修改 原始数据集没有任何异常值,这是我混淆的原因。感谢MrFlick对随机生成的数据的回答,这些数据可以恰当地阐明它。

1 个答案:

答案 0 :(得分:2)

我没有下载数据,而是随机抽样。

set.seed(18)

gg <- expand.grid (
    Methods=c("BC","FD","FDFND","NC"),
    Metrics=c("DM","DTI","LB"),
    Representations=c("CHG","QR","HQR")
)

df <- data.frame(
    gg,
    Values=rnorm(nrow(gg)*50)
)

然后你应该能够用

创建你想要的情节
library(ggplot2)

ggplot(df, aes(x=Representations, y=Values, fill=Methods)) +
    geom_boxplot() +
    stat_summary(fun.y="mean", geom="point", 
        position=position_dodge(width=0.75), color="white") + 
    facet_wrap(~Metrics)

给了我

boxplot

我使用的是ggplot2版本0.9.3.1