I drew a boxplot in the following order:
Test <- data %>%
mutate(across(day, factor, levels=c("7 dpi","3 dpi","14 dpi", "21 dpi"))) %>%
ggplot(aes(x = grp, y = lung, colour = grp))
geom_boxplot(outlier.shape = NA)
scale_fill_viridis(discrete = TRUE, alpha=0.6)
geom_jitter(size=1.5)
facet_wrap(~day,nrow = 1,strip.position = "top")
labs(x="Groups", y = "Lung")
theme(legend.position="none",axis.text.x = element_text(colour="grey20",size=9,angle=0,hjust=.5,vjust=.5,face="plain"),
axis.text.y = element_text(colour="grey20",size=9,angle=0,hjust=1,vjust=0,face="plain"),
axis.title.x = element_text(colour="black",size=10,angle=0,hjust=.5,vjust=0,face="bold"),
axis.title.y = element_text(colour="black",size=10,angle=90,hjust=.5,vjust=.5,face="bold"),
plot.title = element_text(size=18, face = "bold"))
But when I add a line to the chart, the order of the groups changes.I do not know what to do.
anno1.1 <- data.frame(
day="3 dpi",
x=c(1, 1, 2),
xend=c(2, 1, 2),
y=c(5, 5, 5),
yend=c(5, 4.85, 4.85))
anno2.1 <- data.frame(
day="7 dpi",
x=c(2, 2, 6),
xend=c(6, 2, 6),
y=c(5, 5, 5),
yend=c(5, 4.85, 4.85))
anno3.1 <- data.frame(
day="14 dpi",
x=c(2, 2, 6),
xend=c(6, 2, 6),
y=c(5, 5, 5),
yend=c(5, 4.85, 4.85))
Test
geom_segment(data = anno1.1, aes(x = x, y = y, xend=xend, yend=yend), inherit.aes = FALSE)
geom_segment(data = anno2.1, aes(x = x, y = y, xend=xend, yend=yend), inherit.aes = FALSE)
geom_segment(data = anno3.1, aes(x = x, y = y, xend=xend, yend=yend), inherit.aes = FALSE)
theme_classic()
CodePudding user response:
There's no reproducible data shared, so I can't test this solution, but I suggest combining your annotation data frames into a single data frame and specifying the level order as you do in your original data:
anno1.1 <- data.frame(
day="3 dpi",
x=c(1, 1, 2),
xend=c(2, 1, 2),
y=c(5, 5, 5),
yend=c(5, 4.85, 4.85))
anno2.1 <- data.frame(
day="7 dpi",
x=c(2, 2, 6),
xend=c(6, 2, 6),
y=c(5, 5, 5),
yend=c(5, 4.85, 4.85))
anno3.1 <- data.frame(
day="14 dpi",
x=c(2, 2, 6),
xend=c(6, 2, 6),
y=c(5, 5, 5),
yend=c(5, 4.85, 4.85))
anno = rbind(anno1.1, anno2.1, anno3.1) %>%
mutate(across(day, factor, levels=c("7 dpi","3 dpi","14 dpi", "21 dpi")))
# note that the levels in your code do not match the plot -
# probably a copy/paste typo. You probably want to change
# both pieces of code to put 3 dpi before 7 dpi.
# (the `across()` is pointless here, but I keep it for consistency)
# this has the advantage of simplifying your plotting code
Test
geom_segment(data = anno, aes(x = x, y = y, xend=xend, yend=yend), inherit.aes = FALSE)
theme_classic()