ggplot bar graph (multiple variables)

Hi, I was wondering what is the best way to plot these averages side by side using geom_bar.

Thank you.

data.frame(
      Ending_Average = c(0.275, 0.296, 0.259),
   Runner_On_Average = c(0.318, 0.545, 0.222),
              Batter = as.factor(c("Jason Kipnis", "Tyler Naquin",
                                   "Carlos Santana"))
)
1 Like

One possible way is to gather the two average variables into one column. This will allow us to have one x and one y variable.

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

dat <- data.frame(
  Ending_Average = c(0.275, 0.296, 0.259),
  Runner_On_Average = c(0.318, 0.545, 0.222),
  Batter = as.factor(c("Jason Kipnis", "Tyler Naquin",
                       "Carlos Santana"))
)

dat_long <- dat %>%
  gather("Stat", "Value", -Batter)

dat_long
#>           Batter              Stat Value
#> 1   Jason Kipnis    Ending_Average 0.275
#> 2   Tyler Naquin    Ending_Average 0.296
#> 3 Carlos Santana    Ending_Average 0.259
#> 4   Jason Kipnis Runner_On_Average 0.318
#> 5   Tyler Naquin Runner_On_Average 0.545
#> 6 Carlos Santana Runner_On_Average 0.222

For making bars I chose to use geom_col(). geom_col() uses the y value as the height of the bar while geom_bar() essentially counts what is within the y (or you can change the stat to count if you want to keep geom_bar()). Next we use position = "dodge" within geom_col() to make the bars un-stack. By default they will be stacking due to the format of our data and when he used fill = Stat we told ggplot we want to group the data on that variable.

ggplot(dat_long, aes(x = Batter, y = Value, fill = Stat)) +
  geom_col(position = "dodge")

Created on 2019-06-20 by the reprex package (v0.3.0)

3 Likes

That is awesome. Thank you for your help.

1 Like

If your question's been answered (even by you!), would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.