2017-08-03 39 views
0

這已被問及其他帖子,但我還沒有想出如何正確使用position_dodgeggplot2 - 如何在條形圖上居中放置置信區間吧

如何將圖形中每個欄中的每個CI欄居中?

df <- structure(list(Ano = c(2012, 2012, 2012, 2016, 2016, 2016), 
       Grupo = c("Controle", "Tratado", "Total", 
         "Controle", "Tratado", "Total"), 
       Margem_Mediana = c(4.4,3.1, 4.2, 3.8, 2.5, 3.6), 
       Erro_Padrao = c(0.0236, 0.0460, 0.0214, 0.0257, 0.0478, 0.0231)), 
      class = c("tbl_df", "tbl", "data.frame"), 
      row.names = c(NA, -6L), .Names = c("Ano", "Grupo", "Margem_Mediana", "CI")) 


ggplot(df, aes(x = Ano, y = Margem_Mediana, fill = Grupo)) + 
    geom_bar(data = subset(df, Grupo != 'Total'), 
         position = position_dodge(), stat = 'identity') + 
    geom_errorbar(data = subset(df, Grupo != 'Total'), 
           aes(ymin = Margem_Mediana - CI, 
        ymax = Margem_Mediana + CI), 
       width = 1.5, 
       size = 0.5) 
+0

請修改您的代碼,將'df < - '改爲'graf_votos <-'和'.Names = c(「Ano」,「Grupo」,「Margem_Mediana」,「CI」)'改爲'.Names = c (「Ano」,「Grupo」,「Margem_Mediana」,「Erro_Padrao」) – kitman0804

+0

對不起。修正了它 –

回答

2

一個可能的解決方案:

添加position = position_dodge()說法在geom_errorbar,並指定你的酒吧width

ggplot(df, aes(x = Ano, y = Margem_Mediana, fill = Grupo)) + 
    geom_bar(data = subset(df, Grupo != 'Total'), 
      width = 1.5, 
      position = position_dodge(), 
      stat = 'identity') + 
    geom_errorbar(data = subset(df, Grupo != 'Total'), 
       aes(ymin = Margem_Mediana - CI, 
        ymax = Margem_Mediana + CI), 
       width = 1.5, 
       position = position_dodge(), 
       size = 0.5) 

一些搜索(例如this postthis page),代碼可以進一步提高後,

ggplot(subset(df, Grupo != 'Total'), 
     aes(x = as.factor(Ano), y = Margem_Mediana, fill = Grupo)) + 
    geom_bar(width = 0.8, 
      position = position_dodge(), 
      stat = 'identity') + 
    geom_errorbar(aes(ymin = Margem_Mediana - CI, 
         ymax = Margem_Mediana + CI), 
        width = 0.4, 
        position = position_dodge(width = 0.8)) + 
    xlab('Ano') 

也可以使用width參數在position_dodge()控制誤差棒的位置和寬度,並geom_errorbar()

如果您想要居中錯誤欄,則可能需要指定width中的geom_bar(),如width = 0.8 (看起來像0.9是默認值),並在geom_errorbar()內使用position_dodge(width = 0.8)中的相同值(如果您沒有在geom_bar中設置width,則使用0.9)。而widthgeom_errorbar會告訴ggplot錯誤欄的寬度。

+0

有沒有一種方法可以居中放置它,而不會使間隔不與寬度相同? –

+1

@ArthurCarvalhoBrito我編輯了我的答案,但它仍然需要手動設置來居中錯誤欄。 – kitman0804

+1

@ArthurCarvalhoBrito我添加了更多細節。希望它很清楚。 – kitman0804

相關問題