How to create barplot for more than one column using ggplot?

Viewed 84

How can I add more than one column to the barplot using ggplot?

df = data.frame(c("player 1", "player 2", "player 3"),c(1,2,3), c(5,6,7), c(8,9,10))
names(df) = c("player","game 1","game 2", "game 3")

player     game 1  game 2  game 3
-----------------------------------
player 1      1      5       8
player 2      2      6       9
player 3      3      7      10

barplot(colSums(df[,2:4]))

In gglot am not sure how to add more than one x axis aesthetics and y axis is their sum. For example for the above data frame I need to create a barplot with three x axis variable as game 1, game 2 and game 3 and add a label to each bar which is the sum of each x axis variable by player.

please help.

2 Answers

In general, ggplot works best with long data. So pivot it longer (i.e. combine the game variables into a single variable). I'm assuming you want grouped barplots, so you will probably want to use fill = player for that.

library(ggplot2)
library(dplyr)
library(tidyr)

dat <- data.frame(
    player = c("player 1", "player 2", "player 3"),
    game1 = c(1,2,3),
    game2 = c(5,6,7),
    game3 = c(8,9,10)
)

dat %>%
    pivot_longer(cols = contains("game"),
        names_to = "game") %>%
    ggplot(aes(x = game, y = value, fill = player)) +
        geom_col(position = "dodge")

enter image description here

If I did understand correctly, this is what you need. But first, it is not recomemded to use spaces in column names, so I renamed your df. Try these options:

library(tidyverse)
library(magrittr)

df <- data.frame(player = c("player 1", "player 2", "player 3"),
                 game1 = c(1,2,3), 
                 game2 = c(5,6,7), 
                 game3 = c(8,9,10))


option1 <- 
df %>%
  pivot_longer(cols = -player,
               names_to = 'Games',
               values_to = 'Scores') %>%
  ggplot(aes(x = player,
             y = Scores,
             color = Games,
             fill = Games,
             label = Scores)) +
  geom_col(position = 'dodge') +
  geom_text(position = position_dodge(width = 1),
            vjust = -0.5,
            size = 7) +
  scale_y_continuous(limits = c(0,11),
                     breaks = seq(0,10,2))

option 1   

enter image description here

option2 <- 
  df %>%
  mutate(Total = game1 + game2 + game3) %>%
  pivot_longer(cols = -player,
               names_to = 'Games',
               values_to = 'Scores') %>%
    filter(Games == 'Total') %>%
  ggplot(aes(x = player,
             y = Scores,
             color = Games,
             fill = Games,
             label = Scores)) +
  geom_col(show.legend = FALSE) +
  geom_text(vjust = -0.5,
            size = 7,
            show.legend = FALSE) +
  scale_y_continuous(limits = c(0,22),
                     breaks = seq(0,22,2))

option2 

enter image description here

I hope it helped.

Related