I am using ggplot to make three plots using facet_grid(). The default order of the plots & legend is alphabetical. To adjust the order, I factored the relevant variable and confirmed that the intended levels were set. However, the plots still appear in alphabetical order. Factoring did adjust the sample-order in the legend and color assignments, but not the order of the plots.
I found many solutions that add factors within plot creation, but I want to factor my data beforehand so that the plot code stays as simple as possible.
Can anyone explain why my factoring method isn't working for plot arrangement in facets? Is there a simple way to add factor levels before plot creation that facet_grid() will obey?
library(tidyverse)
Sample_Table <- data.frame(
Sample=c(1:9),
Group=c("B", "B", "B", "A", "A", "A", "C", "C", "C"))
data <- data.frame(
Position=c(rep(1:5000,times=3)),
Signal=c(rep(0,times=2000), rep(25,times=1000), rep(0,times=2000),
rep(0,times=2000), rep(50,times=1000), rep(0,times=2000),
rep(0,times=2000), rep(75,times=1000), rep(0,times=2000)),
Group=c(rep("A", times=5000), rep("B", times=5000), rep("C", times=5000))
)
data_factor <- data %>%
dplyr::mutate(Group = factor(Group, levels=c(paste0(unique(Sample_Table$Group)))))
colorscale <- c("#ffe119", "#f58231", "#9A6324")
Plot <- ggplot(data) +
geom_line(aes(x=Position, y=Signal, col=Group), linewidth=.4) +
scale_color_manual(values=c(colorscale)) +
facet_grid(paste0(Group)~.) +
theme_bw() +
theme(axis.text.x = element_blank()) +
theme(
axis.title.x = element_text(margin=margin(t=30)),
legend.title = element_text(colour = "#333333", size=12),
legend.text = element_text(colour = "#333333", size=12)
) +
guides(fill = "none")
Plot_Factored <- ggplot(data_factor) +
geom_line(aes(x=Position, y=Signal, col=Group), linewidth=.4) +
scale_color_manual(values=c(colorscale)) +
facet_grid(paste0(Group)~.) +
theme_bw() +
theme(axis.text.x = element_blank()) +
theme(
axis.title.x = element_text(margin=margin(t=30)),
legend.title = element_text(colour = "#333333", size=12),
legend.text = element_text(colour = "#333333", size=12)
) +
guides(fill = "none")

