r - 添加具有单组值的分类散点图的平均线

标签 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 组添加一条平均线,但我无法找到正确的方法。我已经尝试过 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

有人对如何解决这个问题有任何建议吗?

谢谢。

最佳答案

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

# 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

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

关于r - 添加具有单组值的分类散点图的平均线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24487007/

相关文章:

r - 在 R 中加载具有最新日期的文件

R代码根据概率/比例随机分配数据

r - 绘图点的边框颜色-R绘图

python - 为什么我的散点图没有显示颜色?

r,ggplot2,形状/颜色。它们之间有什么区别?

r - 使用 ggplot2 表示散点图中每个点的小饼图

r - data.table 在 R 中复制表

r - 所有标点符号周围都留有空格,但撇号除外

r - ggplot facet_wrap 选定的 data.frame 列?

r - geom_statdensity2d 具有特定的轮廓?