使用单个组值添加分类散点图的平均线

时间:2014-06-30 09:32:13

标签: r ggplot2 scatter-plot

我有一个像这样的分类散点图:

enter image description here

我使用以下代码在R中生成的

(使用ggplot2库):

data <- runif(50, 13, 17)
factors <- as.factor(sample(1:3, 50, replace = TRUE))
groups <- as.factor(sample(1:3, 50, replace = TRUE))
data_table <- data.frame(data, factors)
g <- ggplot(data_table, aes(y = data_table[, 1], x = data_table[, 2], colour = groups)) + geom_point(size = 1.5)

我正在尝试为每个x-group添加平均线,但我无法找到正确的方法。我已经尝试了this question中描述的过程,但它不起作用,我认为因为我的x组每个都由一个x值组成,我相信这个过程应该是不同的

更详细的说明,如果我添加:

+ geom_line(stat = "hline", yintercept = "mean", aes(colour = data_table[, 2]))

到上一个代码行,它给出了以下错误: geom_path:每个组只包含一个观察。你需要调整群体审美吗?

如果我尝试在该问题的答案中建议的程序,请添加:

+ geom_errorbar(stat = "hline", yintercept = "mean", width=0.8, aes(ymax=..y..,ymin=..y..))

到我的初始代码(我删除了geom_jitter(position = position_jitter(width = 0.4))段代码,因为它在我的数据图中添加了随机点),每组得到三行(每行对应三个组的平均值)红色,绿色,蓝色表示特定的x组),如下图所示:

enter image description here

有没有人对如何解决此问题有任何建议?

谢谢。

1 个答案:

答案 0 :(得分:3)

以下代码应该为您提供所需的结果:

# creating reproducible data
set.seed(1)
data <- runif(50, 13, 17)
factors <- as.factor(sample(1:3, 50, replace = TRUE))
groups <- as.factor(sample(1:3, 50, replace = TRUE))
data_table <- data.frame(data, factors, groups)

# creating the plot
ggplot(data=data_table, aes(x=factor(factors), y=data, color=groups)) + 
  geom_point() +
  geom_errorbar(stat = "hline", yintercept = "mean", width=0.6, aes(ymax=..y.., ymin=..y.., group=factor(factors)), color="black")

给出: enter image description here

检查方法是否正确:

> by(data_table$data, data_table$factors, mean)
data_table$factors: 1
[1] 15.12186
------------------------------------------------------------------------------------------------- 
data_table$factors: 2
[1] 15.03746
------------------------------------------------------------------------------------------------- 
data_table$factors: 3
[1] 15.24869

得出的结论是平均值正确地显示出来。


根据@rrs的建议,您也可以将其与箱线图结合使用:

ggplot(data=data_table, aes(x=factor(factors), y=data, color=groups)) + 
  geom_boxplot(aes(middle=mean(data), color=NULL)) +
  geom_point(size=2.5)

给出: enter image description here

然而,中间的线代表中位数而不是平均值。