ggplot2:添加每组平均值的线
library(ggplot2)
orderX <- c("A" = 1, "B" = 2, "C" = 3)
y <- rnorm(20)
x <- as.character(1:20)
group <- c(rep("A", 5), rep("B", 7), rep("C", 5), rep("A", 3))
df <- data.frame(x, y, group)
df$lvls <- as.numeric(orderX[df$group])
ggplot(data = df, aes(x=reorder(df$x, df$lvls), y=y)) +
geom_point(aes(colour = group)) +
geom_line(stat = "hline", yintercept = "mean", aes(colour = group))
我想创建一个像这样的图表:
当我不需要重新排序 X 的值时,这确实有效,但是,当我一定要使用重新排序,它不再起作用了。
library(ggplot2)
orderX <- c("A" = 1, "B" = 2, "C" = 3)
y <- rnorm(20)
x <- as.character(1:20)
group <- c(rep("A", 5), rep("B", 7), rep("C", 5), rep("A", 3))
df <- data.frame(x, y, group)
df$lvls <- as.numeric(orderX[df$group])
ggplot(data = df, aes(x=reorder(df$x, df$lvls), y=y)) +
geom_point(aes(colour = group)) +
geom_line(stat = "hline", yintercept = "mean", aes(colour = group))
I want to create a graph like this:
This does work, when I do not need to reorder the values of X, however, when I do use reorder, it doesn't work anymore.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从您的问题来看,我认为这个
df$x
与您的数据根本无关,特别是如果您可以重新排序的话。如何仅使用group
作为x,并使用jitter
实际的x位置来分隔点:我使用errorbar而不是h_line(并将ymax和ymin折叠到y)因为 hline 很复杂。如果有人对此部分有更好的解决方案,我很乐意看到。
更新
如果您想保留 X 的顺序,请尝试此解决方案(修改后X)
From your question, I don't this
df$x
is relevant to your data at all, especially if you can re-order it. How about just usinggroup
as x, andjitter
the actual x position to separate the points:I have used errorbar instead of h_line (and collapsed the ymax and ymin to y) since hline is complex. If anyone has a better solution to that part, I'd love to see.
update
If you want to preserve the order of X, try this solution (with modified X)
遗憾的是,从 ggplot2 2.x 开始,这种方法已被破坏。
以下代码完全提供了我想要的内容,并预先进行了一些额外的计算:
生成的图像:
As of ggplot2 2.x this approach is unfortunately broken.
The following code provides exactly what I wanted, with some extra calculations up front:
The resulting image: