2

My dataframe looks like this:

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

I managed to create a stacked bar with wins, draws, losses with ggplot: enter image description here

Using the following code:

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()

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: enter image description here

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.

Any help is greatly appreciated!

yannick
  • 185
  • 1
  • 1
  • 7

1 Answers1

3

As a staring point

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 Created on 2020-06-18 by the reprex package (v0.3.0)

UseR10085
  • 7,120
  • 3
  • 24
  • 54
Bruno
  • 4,109
  • 1
  • 9
  • 27