2010-11-22 119 views
19
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)) 

我想创建这样一个图: graph with averages for each groupGGPLOT2:对于平均加线每组

这并不工作,当我不需要然而重新排序X的值,当我做使用重新排序,它不再工作。

+0

我觉得你订货的用法是错误的在这里,因为它只会重新排列X,而不是组或Y.这会用错误的y画出错误的x! – 2010-11-22 11:41:03

+0

除非X不代表索引,否则在剧情中不要使用它(使用抖动代替?) – 2010-11-22 11:53:24

+0

然后我使用重排是错误的。在我的实际数据中,x上的值是每个单独测量的标签,我确实希望看到。这些标签在组内的顺序无关紧要。 – wligtenberg 2010-11-22 12:20:53

回答

3

由于g gplot2 2.x这种方法不幸中断。

下面的代码提供了正是我想要的,有一些额外的计算前面:

library(ggplot2) 
library(data.table) 

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)) 
dt <- data.table(x, y, group) 
dt[, lvls := as.numeric(orderX[group])] 
dt[, average := mean(y), by = group] 
dt[, x := reorder(x, lvls)] 
dt[, xbegin := names(which(attr(dt$x, "scores") == unique(lvls)))[1], by = group] 
dt[, xend := names(which(attr(dt$x, "scores") == unique(lvls)))[length(x)], by = group] 

ggplot(data = dt, aes(x=x, y=y)) + 
    geom_point(aes(colour = group)) + 
    facet_grid(.~group,space="free",scales="free_x") + 
    geom_segment(aes(x = xbegin, xend = xend, y = average, yend = average, group = group, colour = group)) 

产生的图像:

enter image description here

+3

我不确定这是否会帮助你的确切情况,但我用ggplot2 v2.1.0发现的一个类似问题的新解决方案是'stat_summary(fun.y =“mean”,fun.ymin =“mean”,fun.ymax =“mean”,size = 0.3,geom =“crossbar” )'。 – 2016-03-24 18:42:33

+0

我试过了,它会在x轴上为每个项目创建水平线条。原因是x轴是离散的。 – wligtenberg 2016-03-25 09:40:50

16

从你的问题,我不这df$x是根据你的数据,尤其是如果你可以重新订购它。如何只使用group为X,jitter实际x位置,以点分开:

ggplot(data=df, aes(x=group,y=y,color=group)) + geom_point() + 
geom_jitter(position = position_jitter(width = 0.4)) + 
geom_errorbar(stat = "hline", yintercept = "mean", 
    width=0.8,aes(ymax=..y..,ymin=..y..)) 

我用errorbar代替h_line(和折叠的ymax和ymin的为y),因为HLINE是复杂的。如果有人有更好的解决方案,我很乐意看到。

alt text


更新

如果您想保留X的顺序,尝试此解决方案(与修改的X)

df$x = factor(df$x) 

ggplot(data = df, aes(x, y, group=group)) + 
facet_grid(.~group,space="free",scales="free_x") + 
geom_point() + 
geom_line(stat = "hline", yintercept = "mean") 

alt text

+0

这确实是我想要的,但是,我确实希望能够看到x尺度上的原始x值。 – wligtenberg 2010-11-22 12:43:32

+0

当您执行上述重新排序时,您的数据会混淆。您应该对原始数据框进行排序,而不仅仅是x值。你想要在你的图表中交错的x值吗?如果他们是,你想在哪里放置平均值? – 2010-11-22 13:56:34

+0

你在哪里找到关于geom_line(stat =“hline”,yintercept =“mean”)的文档?这真的很酷,我从来没有见过。 – 2010-11-22 15:04:34