#Sample data
set.seed(42)
DB = data.frame(Group =c(rep("1",16),
rep("2",4)) ,
Score1 = sample(1:20,20, replace = T),
Score2 = sample(1:20,20, replace = T),
Score3 = sample(1:20,20, replace = T),
Score4 = sample(1:20,20, replace = T))
I want to plot two bar charts comparing the mean of each score in both groups. So the right side will be with a Title "Group 1 mean scores" and left side (left barchart) is "Group 2 mean scores" Thanks.
CodePudding user response:
You can pivot to long format and use stat = "summary"
library(tidyverse)
DB %>%
pivot_longer(-1, names_to = "Score") %>%
ggplot(aes(Group, value, fill = Score))
geom_bar(position = position_dodge(width = 0.8, preserve = "total"),
stat = "summary", fun = mean, width = 0.6)
scale_fill_brewer(palette = "Set2")
theme_minimal(base_size = 20)
Or if you prefer facets, you can do:
library(tidyverse)
DB %>%
pivot_longer(-1, names_to = "Score") %>%
mutate(Group = paste("Group", Group)) %>%
ggplot(aes(Score, value, fill = Score))
geom_bar(stat = "summary", fun = mean, width = 0.6)
scale_fill_brewer(palette = "Set2", guide = "none")
facet_grid(.~Group)
theme_bw(base_size = 20)
Created on 2022-11-13 with reprex v2.0.2