Home > Back-end >  How to do a three group boxplot in R with 3 columns of a dataframe?
How to do a three group boxplot in R with 3 columns of a dataframe?

Time:04-01

I'm calculating some stats for 3 groups - all, male, and female. I've stored them into a dataframe called stats_df that has each group as a column header with the stats as the row data. I need to do a boxplot (my most current attempt is included in the code) that has all 3 groups represented as boxes, but I can't seem to figure it out and no online tutorials are helping.

enter image description here

all_stats <- c(all_mean, all_median, all_mode, all_25, all_50, all_75)
female_stats <- c(female_mean, female_median, female_mode, female_25, female_50, female_75)
male_stats <- c(male_mean, male_median, male_mode, male_25, male_50, male_75)

stats_df <- data.frame(all_stats, female_stats, male_stats)


boxplot(all_stats ~ male_stats,
        data=stats_df, 
        main="Stats Boxplot",
        xlab="Group", 
        ylab="Number")

CodePudding user response:

You can use the following code:

stats_df <- data.frame(all_stats = c(35.19, 32, 29, 26, 32, 50),
                       female_stats = c(36.23, 32, 32, 24, 32, 52),
                       male_stats = c(33.5, 32, 29, 28.5, 32, 39.5))

library(tidyverse)
stats_df %>%
  ggplot()  
  geom_boxplot(aes(x = "all_stats", y = all_stats))  
  geom_boxplot(aes(x = "female_stats", y = female_stats))  
  geom_boxplot(aes(x = "male_stats", y = male_stats))  
  xlab("Group")  
  ylab("Number")  
  ggtitle("Stats Boxplot")

Output:

enter image description here

  • Related