Search code examples
rggplot2facet-wrap

Prevent reordering within facet_wrap()


I have an issue with my ggplot() reordering the data. I have an example code below. I have data, and reordered the factors in feed to my content, but after the str_extract() in facet_wrap(), the data gets reordered back before I reordered it. Is there a way to prevent that from occurring? For my actual code, it is important for me to use regex within the facet_wrap() in ggplot,

data <- chickwts
data <- mutate(data, time = 1:nrow(data))
lvl <- c("linseed", "meatmeal", "sunflower", "soybean", 
         "casein", "horsebean")
data$feed <- factor(data$feed, levels = lvl)
ggplot(data, aes(x = time, y = weight, color = feed)) +
    geom_line(size = 1) + geom_point(size = 1.75) +
    facet_wrap(~str_extract(feed,"[a-z]+"))

Solution

  • You could put the factor inside the facet_wrap:

    ggplot(data, aes(x = time, y = weight, color = feed)) +
        geom_line(size = 1) + geom_point(size = 1.75) +
        facet_wrap(~ factor(str_extract(feed,"[a-z]+"), levels = lvl))
    

    enter image description here