Reputation: 11
This is my first R attempt. I want to use stat_compare_means to compare means within subgroups as well as means from different subgroups. And I need the x-axis labeled by Treatment. I am aiming for some thing like this
My data looks like the following
A tibble: 9 x 3
Treatment Group Count
<chr> <chr> <dbl>
1 + a 12
2 + a 13
3 + a 11
4 + b 14
5 + b 15
6 + b 15
7 - c 22
8 - c 24
9 - c 21
I treid several attemps with ggbarplot and geom_bar but none worked. Is my plan even possible with stat_compare_means? Any help is appreciated.
My last try was this:
library(ggpubr)
library(ggplot2)
df <- structure(list(Treatment = c("+", "+", "+", "+", "+", "+", "-", "-", "-"),
Group = c("a", "a", "a", "b", "b", "b", "c", "c", "c"),
Count = c(12, 13, 11, 14, 15, 15, 22, 24, 21)), row.names = c(NA, -9), class = "data.frame")
ggbarplot(df, x = "Treatment", y = "Count", add = "mean_se", error.plot = "upper_errorbar",
color = "Group",
position = position_dodge(0.8))+
stat_compare_means(df, comparisons = list(c("a","b" ), c("a","c"),c("b","c")),
label = "p.signif")
Which returns in
Computation failed in `stat_signif()`:
Missing value, where TRUE/FALSE is needed
Upvotes: 1
Views: 2064
Reputation: 39585
Try something like this:
library(ggpubr)
library(ggplot2)
#Comp
my_comparisons = list( c("+.a","+.b"),c("+.a","-.c"),c("+.b","-.c"))
#Plot
ggplot(df,aes(x=interaction(Treatment,Group),y=Count,fill=Group,group=Group))+
geom_boxplot(position = position_dodge2(width = 0.5,preserve = 'single'))+
theme_bw()+
stat_compare_means(comparisons = my_comparisons,
method = 't.test')+
theme(legend.position = 'top',
panel.grid = element_blank(),
axis.text = element_text(face='bold',color='black'),
axis.title = element_text(face='bold',color='black'),
strip.text = element_text(face='bold',color='black'),
legend.text = element_text(face='bold',color='black'),
legend.title = element_text(face='bold',color='black'),
plot.title = element_text(face='bold',color='black',hjust=0.5))+
ggtitle('My plot')
Output:
Some data used:
#Data
df <- structure(list(Treatment = c("+", "+", "+", "+", "+", "+", "-",
"-", "-"), Group = c("a", "a", "a", "b", "b", "b", "c", "c",
"c"), Count = c(12L, 13L, 11L, 14L, 15L, 15L, 22L, 24L, 21L)), row.names = c(NA,
-9L), class = "data.frame")
Upvotes: 1