代码之家  ›  专栏  ›  技术社区  ›  C8H10N4O2

堆叠条形图中的标签颠倒错误

  •  1
  • C8H10N4O2  · 技术社区  · 7 年前

    enter image description here

    示例数据集:

    library(scales)
    library(ggplot2)
    types <- c('Mostly Satisfied','Somewhat satisfied','Unsatisfied')
    df_summ <- data.frame(cust_type = factor(types, levels=types),
                          cust_count = c(1.2e3, 2.3e3, 3.4e3)
                          )
    df_summ$percent_of_file <- df_summ$cust_count/sum(df_summ$cust_count)
    df_summ$label_txt <- paste0(df_summ$cust_type,': ',comma(df_summ$cust_count),' (',
                                percent(df_summ$percent_of_file),')')
    
    # I need a dummy value for the x axis
    df_summ$group <- 'All customers'
    

    我的绘图代码:

    ggplot(df_summ,
           aes(x=group, y = cust_count, label=label_txt))+
      geom_bar(aes(fill=cust_type),position='stack',stat='identity')+
      geom_text(size = 4, 
                position = position_stack(vjust = 0.5,
                                      reverse=TRUE) # changing to reverse=FALSE doesn't help
                )+
      scale_fill_manual(values = setNames(c('green','beige','salmon'), types),
                        guide=FALSE
      ) +
      labs( x = NULL,
            y = NULL,
            title = 'Composition of customer base') +
      theme_minimal() +
      theme ( panel.grid.major = element_blank(), 
                panel.grid.minor = element_blank(),
                axis.text.x=element_blank(),
                axis.ticks.x=element_blank(),
                axis.text.y=element_blank(),
                axis.ticks.y=element_blank()
              )
    

    我的问题有点像 this question ,但带有条形图,以及解决方案(使用 position_stack() )这对我没有帮助。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Franziska W.    7 年前

    我想补充一点 fill = cust_type label = label_txt 从建筑美学的角度 ggplot() aes(label = label_txt) geom_text() reverse = TRUE reverse = FALSE . 然后,绘图的R代码应如下所示,并有望正常工作:

    ggplot(
      data = df_summ
      ,aes(
        x = group
        ,y = cust_count
        ,fill = cust_type)) +
    geom_bar(
      position = 'stack'
      ,stat = 'identity') +
    geom_text(
      aes(label = label_txt)
      ,size = 4
      ,position = position_stack(
        vjust = 0.5
        ,reverse = FALSE)) +
    scale_fill_manual(
      values = setNames(
        c('green','beige','salmon')
        ,types)
      ,guide = FALSE) +
    labs(
      x = NULL
      ,y = NULL
      ,title = 'Composition of customer base') +
    theme_minimal() +
    theme(
      panel.grid.major = element_blank()
      ,panel.grid.minor = element_blank()
      ,axis.text.x = element_blank()
      ,axis.ticks.x = element_blank()
      ,axis.text.y = element_blank()
      ,axis.ticks.y = element_blank()); 
    
    推荐文章