2016-02-16 26 views
2

我的條形圖出現問題 - 錯誤欄僅出現在分組變量的列的角上,而不是以集中的方式顯示在列上。我使用的代碼是這樣的:將錯誤欄放在ggplot中的列中心的問題()

a <- data.frame (Cond = c("In", "In", "Out", "Out"), 
       Temp = c("Hot", "Cool", "Hot", "Cool"), 
       Score = c(.03, -.15, 0.84, 0.25), 
       SE = c(.02, .08, .14, .12)) 
a.bar <- ggplot (data = a, aes(x = Cond, y = Score, fill = Temp)) + 
      theme_bw() + theme(panel.grid = element_blank()) + 
      coord_cartesian (ylim = c(-0.5, 1)) + 
      geom_bar (aes(fill = Temp), stat = "identity", position = "dodge", width = .5) + 
      geom_errorbar (aes(ymin = Score - SE, ymax = Score + SE, group = Cond), position = position_dodge(.9), width = .08) + 
      labs(y = "Scores" , x = "Cond") + 
      scale_y_continuous (breaks = pretty_breaks(n=8)) + 
      theme(legend.title = element_blank()) + 
      theme(legend.position = "right") 

替代代碼我已經盡力了,我不能讓任工作,包括增加「show.legend = FALSE」來geom_bar();添加「facet_wrap(〜Cond)」plot.a;並在ggplot(aes())中引入「fill = Temp」。 最接近的溶液是當我改變position_dodge()參數轉換爲:

geom_bar (aes(fill = Temp), stat = "identity", position = position_dodge(width = .5)) + 
geom_errorbar (aes(ymin = Score - SE, ymax = Score + SE, group = Cond), position = position_dodge(.5), width = .08) + 

(代碼的其餘部分保持不變)。這將誤差線移向了柱的中心,但也將柱移向了彼此,最終使它們重疊(見附圖)。 see attached figure

我非常感謝這方面的幫助。

謝謝!

回答

3

不錯的問題。一對夫婦的意見:

  1. 一般情況下,這是一個很好的做法,設置在原ggplot()呼叫你所有的美觀,且僅在必要時對個別geom_xyz()調用不同的美學覆蓋它們。在您的代碼中,您將填充美學設置爲兩次,一次在ggplot之間,一次在geom_bar之間。您還可以在geom_errorbar()中設置組審美。我不認爲任何這些事情都是最終的問題,但他們確實使調試代碼更加困難。

  2. 的主要問題是,width論點geom_bar必須匹配內部geom_errorbarposition_dodge()說法。所以,如果你有

    # ... 
    geom_bar(stat = "identity", position = "dodge", width = 0.5) 
    # ... 
    

    然後你必須確保你的geom_errorbar()看起來像

    # ... 
    geom_errorbar(width = .08, position = position_dodge(0.5)) 
    # ... 
    

全部放在一起:

require(ggplot2) 
require(scales) 

# define data 
a <- data.frame (Cond = c("In", "In", "Out", "Out"), 
       Temp = c("Hot", "Cool", "Hot", "Cool"), 
       Score = c(.03, -.15, 0.84, 0.25), 
       SE = c(.02, .08, .14, .12)) 

# return plot with everything except error bars 
a.bar <- ggplot (data = a, aes(x = Cond, 
           y = Score, 
           fill = Temp, 
           ymin = Score - SE, 
           ymax = Score + SE)) + 
      theme_bw() + 
      theme(panel.grid = element_blank()) + 
      coord_cartesian(ylim = c(-0.5, 1)) + 
      # manually setting the width means we will have to tell geom_errorbar() about the new width 
      geom_bar(stat = "identity", position = "dodge", width = 0.5) + 
      labs(y = "Scores", x = "Cond") + 
      scale_y_continuous(breaks = pretty_breaks(n = 8)) + 
      theme(legend.title = element_blank()) + 
      theme(legend.position = "right") 

# show plot w/ errorbars, note that argument to position_dodge is same as width supplied above 
a.bar + geom_errorbar(width = .08, position = position_dodge(0.5)) 

# save results 
ggsave('SO_35424162.png') 

Final graph