【问题标题】:Add Data Labels to Stacked Bar Chart in R [duplicate]将数据标签添加到R中的堆积条形图[重复]
【发布时间】:2020-06-18 10:07:59
【问题描述】:

我的数据框如下所示:

team  played  wins  draws  losses  scored  conceded
 A       5      3     1       1       12       4
 B       7      3     3       1       16       8      
 C       3      0     1       2       2        14
 D       5      2     2       1       12       7

我设法用 ggplot 创建了一个包含赢、平、输的堆叠条:

使用以下代码:

df %>% select(team,wins,draws,losses) %>% 
  pivot_longer(cols = -team) %>% 
  mutate(name = factor(name, levels = c("wins", "draws", "losses"))) %>% 
  ggplot(aes(x = team, y=value, fill = name)) + 
  geom_col(position = position_stack(reverse = TRUE)) + coord_flip()

现在,我正在尝试添加数据标签。我尝试使用+ geom_text(label = name),但这不起作用。我希望最终结果如下所示:

如果可以在每列右侧添加总数据标签(即赢、平、输的总和),那就太好了。

非常感谢任何帮助!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    作为一个起点

    library(tidyverse)
    
    df_example <-  read.table(text="team  played  wins  draws  losses  scored  conceded
    A       5      3     1       1       12       4
    B       7      3     3       1       16       8      
    C       3      0     1       2       2        14
    D       5      2     2       1       12       7", header=T)
    
    
    totals <- df_example %>%
      select(team,wins,draws,losses) %>% 
      pivot_longer(cols = -team) %>%
      mutate(name = factor(name, levels = c("wins", "draws", "losses"))) %>%
      group_by(team) %>%
      summarize(total = sum(value))  
    
    
    df_example %>%
      select(team,wins,draws,losses) %>% 
      pivot_longer(cols = -team) %>%
      mutate(name = factor(name, levels = c("wins", "draws", "losses"))) %>% 
      ggplot(aes(x = team, y=value, fill = name,label = name)) +
      geom_col(position = position_stack(reverse = TRUE)) +
      coord_flip() +
      geom_text(aes(label = value,family = "serif"), position = position_stack(reverse = TRUE,vjust = 0.5))+
      theme_bw() + 
      theme(text = element_text(family = "serif", color = "black", size = 15))+ 
      theme(axis.text = element_text(family = "serif", color = "black", size = 12))+
      geom_text(aes(team, total + 0.1, label = total, fill = NULL,family = "serif"), data = totals)
    

    reprex package (v0.3.0) 于 2020 年 6 月 18 日创建

    【讨论】:

    • 由于无法添加新答案,因此我已编辑您的答案。
    • @BappaDas 没问题
    猜你喜欢
    • 2011-04-07
    • 2017-11-27
    • 2021-03-26
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多