2010-11-22 120 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