简体   繁体   中英

Stacked Bar Plot in R for Head-To-Head Statistics

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 would like a stacked bar for each team, with "wins" at the bottom, upon which "draws" is stacked, upon which "losses" is stacked. How do I achieve that? It should look like this: 在此处输入图像描述

You can use following code

library(tidyverse)

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

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

在此处输入图像描述

Close to what you want:

df <- tibble::tribble(
        ~team, ~played, ~wins, ~draws, ~losses, ~scored, ~conceded,
          "A",      5L,    3L,     1L,      1L,     12L,        4L,
          "B",      7L,    3L,     3L,      1L,     16L,        8L,
          "C",      3L,    0L,     1L,      2L,      2L,       14L,
          "D",      5L,    2L,     2L,      1L,     12L,        7L
        )

library(ggthemes)
df %>% 
  pivot_longer(wins:losses) %>% 
  mutate(name = factor(name, levels = c("wins", "draws", "losses"))) %>% 
  ggplot(aes(y = fct_reorder(team, -order(team)), x = value, fill = name)) +
  geom_col(position = position_stack(reverse = TRUE)) + 
  labs(y="team", x="") +
  theme_tufte() +
  theme(panel.grid.major.x = element_line(color = "black"),legend.position="top", legend.title = element_blank())

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM