2013-07-26 12 views
0

喜有此數據集:如何在此圖上繪製錯誤條並更改覆蓋圖?

tdat=structure(list(Condition = structure(c(1L, 3L, 2L, 1L, 3L, 2L, 
1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 
3L, 2L, 1L, 3L, 2L), .Label = c("AS", "Dup", "MCH"), class = "factor"), 
    variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 
    3L, 3L, 3L), .Label = c("Bot", "Top", "All"), class = "factor"), 
    value = c(1.782726022, 1, 2.267946449, 1.095240234, 1, 1.103630141, 
    1.392545278, 1, 0.854984833, 4.5163067, 1, 4.649271897, 0.769428018, 
    1, 0.483117123, 0.363854608, 1, 0.195799358, 0.673186975, 
    1, 1.661568993, 1.174998373, 1, 1.095026419, 1.278455823, 
    1, 0.634152231)), .Names = c("Condition", "variable", "value" 
), row.names = c(NA, -27L), class = "data.frame") 

> head(tdat) 
    Condition variable value 
1  AS  Bot 1.782726 
2  MCH  Bot 1.000000 
3  Dup  Bot 2.267946 
4  AS  Bot 1.095240 
5  MCH  Bot 1.000000 
6  Dup  Bot 1.103630 

我可以繪製它像使用此代碼:

ggplot(tdat, aes(x=interaction(Condition,variable,drop=TRUE,sep='-'), y=value, 
       fill=Condition)) + 
       geom_point() + 
       scale_color_discrete(name='interaction levels')+ 
     stat_summary(fun.y='mean', geom='bar', 
       aes(label=signif(..y..,4),x=as.integer(interaction(Condition,variable)))) 

http://postimg.org/image/5fwdwuu5t/

我有2個問題:

  1. 如何改變覆蓋這樣的黑點不被 條形圖隱藏(3分應該是每列可見)

  2. 如何使用從黑點的標準偏差 條上添加垂直errorbar?

回答

2

像這樣:

tdat$x <- with(tdat,interaction(Condition,variable,drop=TRUE,sep='-')) 
tdat_err <- ddply(tdat,.(x), 
        summarise,ymin = mean(value) - sd(value), 
          ymax = mean(value) + sd(value)) 

ggplot(tdat, aes(x=x, y=value)) + 
     stat_summary(fun.y='mean', geom='bar', 
       aes(label=signif(..y..,4),fill=Condition)) + 
     geom_point() + 
     geom_errorbar(data = tdat_err,aes(x = x,ymin = ymin,ymax = ymax,y = NULL),width = 0.5) + 
     labs(fill = 'Interaction Levels') 

enter image description here

我有點清理你的代碼。如果在ggplot()調用之外移動任何無關的計算,則會遇到更少的問題。最好先創建新的x變量。這一切都更可讀。

覆蓋問題只需要重新排序圖層。

請注意,當您映射fill而不是colour(這是一個非常常見的錯誤)時,您正在使用scale_colour_*

唯一的其他「訣竅」是y的解映射。通常情況下,當事情變得棘手時,我忽略頂層ggplot中的aes,完全調用以確保每層只獲得它所需的美觀。

錯誤欄再次我傾向於首先創建ggplot之外的數據框架。我覺得更清潔,更容易閱讀。

+0

一旦你知道像'mean_sdl'功能,代碼實際上是非常容易閱讀。 – Roland

+0

@Roland是的,'stat_summary'沒有什麼錯,這只是我個人的偏好而已。 – joran

4

我並不太贊成將混合誤差條與條形圖。

在ggplot2 geoms按照您將它們添加到圖中的順序繪製。所以,爲了讓這些點不隱藏,把它們添加到條之後。使用它們

ggplot(tdat, aes(x=interaction(Condition,variable,drop=TRUE,sep='-'), y=value, 
       fill=Condition)) + 
    stat_summary(fun.data="mean_sdl", mult=1, geom="errorbar") + 
    stat_summary(fun.y='mean', geom='bar') + 
    geom_point(show_guide=FALSE) + 
    scale_fill_discrete(name='interaction levels') 

enter image description here