The codes work when there are observations for all group in the dataset. However, when a group of data is NA, the error bars will be displaced. Here is an example:
library(ggpubr)
# Load the ToothGrowth dataset
data(ToothGrowth)
ggbarplot(ToothGrowth, x = "dose", y = "len",
add = "mean_se",
color = "supp", palette = "jco",
position = position_dodge(0.8)
) +
ggtitle("no NA in dataset")
# Motified dataset
ToothGrowth$len[ToothGrowth$dose == 2 & ToothGrowth$supp == "VC"] <- NA
head(ToothGrowth)
ggbarplot(ToothGrowth, x = "dose", y = "len",
add = "mean_se",
color = "supp", palette = "jco",
position = position_dodge(0.8)
)+
ggtitle("one group is NA")
You could fix your issue by setting preserve = "single"
in position_dodge()
:
library(ggpubr)
#> Loading required package: ggplot2
ToothGrowth$len[ToothGrowth$dose == 2 & ToothGrowth$supp == "VC"] <- NA
ggbarplot(ToothGrowth,
x = "dose", y = "len",
add = "mean_se",
color = "supp", palette = "jco",
position = position_dodge(0.8, preserve = "single")
) +
ggtitle("one group is NA")