将数据标签添加到R中的堆叠条形图

时间:2020-06-18 10:07:59

标签: r ggplot2

我的数据框如下:

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创建了一个带有胜利,失败和失败的堆叠式条形: enter image description here

使用以下代码:

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),但这不起作用。我希望最终结果如下所示: enter image description here

如果可以在每列的右侧添加总的数据标签(即获胜,平局,亏损之和),那就太好了。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分: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)

enter image description here reprex package(v0.3.0)于2020-06-18创建