Home > Net >  How do I create a bar chart where y axis measures mean of a variable?
How do I create a bar chart where y axis measures mean of a variable?

Time:08-26

barplot I want to recreate

The y-axis I have is a variable of type 'double'. The x-axis is of type factor (changed it from character).

I made this plot years ago and have no idea how to do it in either the base or ggplot2 package. I want to get the mean of the y axis variable.

Help?

CodePudding user response:

Here you go. First in base R and second in ggplot2:

library(tidyverse)

shoot_data <- data.frame("result" = c("Winner", "Loser"),
                         "avrgtime" = c(8.48, 9.53))

# Plot with base R
barplot(shoot_data$avrgtime ~ shoot_data$result,
        ylab = "Average Time to Shoot",
        xlab = "Game Result",
        ylim = c(0,10))

# Plot with GGplot2
shoot_data %>%
  ggplot(aes(x = result, y = avrgtime)) 
  geom_bar(stat = "identity") 
  ylab("Average Time to Shoot") 
  xlab("Game Result")

Created on 2022-08-26 with reprex v2.0.2

CodePudding user response:

In ggplot you can use the option stat="summary" and fun="mean" to automatically get the averages on your y-axis. Here an example without average values and with average values:

df <- data.frame(result = c("Lost", "Win", "Lost", "Win"),
                 shoot_time = c(8, 6, 9, 7))  

library(ggplot2)
# Just y value on barplot
ggplot(df, aes(x = result, y = shoot_time))  
  geom_bar(stat = "identity")  
  labs(x = "Game Result", y = "Total Time to Shoot")

# Averages on y-axis
ggplot(df, aes(x = result, y = shoot_time))  
  geom_bar(stat = "summary", fun = "mean")  
  labs(x = "Game Result", y = "Average Time to Shoot")

Created on 2022-08-26 with reprex v2.0.2

  • Related