2017-08-03 37 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

相关问题