将数据标签添加到R中的堆叠条形图 [英] Add Data Labels to Stacked Bar Chart in R

查看:55
本文介绍了将数据标签添加到R中的堆叠条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框如下:

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

I managed to create a stacked bar with wins, draws, losses with 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),但这不起作用.我希望最终结果如下所示:

Now, I was trying to add data labels. I tried using + geom_text(label = name) but that doesn't work. I'd like the final result to look as follows:

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

If it's possible to add total data labels (i.e. sum of wins, draws, losses) as seen on the right of each column, that'd be great.

任何帮助将不胜感激!

推荐答案

凝视点

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软件包(v0.3.0)

Created on 2020-06-18 by the reprex package (v0.3.0)

这篇关于将数据标签添加到R中的堆叠条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆