I have seen the solutions to reordering subplots when it's just one object being plotted (e.g. mydata), but I am not sure how to do this when there are multiple objects being plotted (in this instance, mydata1 and mydata2). I would like to switch the order of the violins such that Treatment2 is on the left, and Treatment1 is on the right, instead of vice-versa like I currently have it:
mycp <- ggplot() + geom_violin(data = mydata1, aes(x= treatment, y = Myc_List1, fill = Myc_List1, colour="Myc Pathway (Treatment1)")) + 
  geom_violin(data = mydata2, aes(x= treatment, y = Myc_List1, fill = Myc_List1, colour = "Myc Pathway (Treatment2)")) 

When I try solutions such as in Ordering of bars in ggplot, or the following solution posed at https://www.r-graph-gallery.com/22-order-boxplot-labels-by-names.html, this graph remains unchanged.
Hopefully this makes sense, and thank you for reading!
Here is another solution as well from https://www.datanovia.com/en/blog/how-to-change-ggplot-legend-order/
mydata$treatment<- factor(mydata$treatment, levels = c("Treatment2", "Treatment1"))
I'm not sure how to reorder factors in this case, but you can change the x axis scale to get the desired result, e.g.
library(tidyverse)
data("Puromycin")
dat1 <- Puromycin %>% 
  filter(state == "treated")
dat2 <- Puromycin %>% 
  filter(state == "untreated")
mycp <- ggplot() +
  geom_violin(data = dat1, aes(x= state, y = conc, colour = "Puromycin (Treatment1)")) + 
  geom_violin(data = dat2, aes(x= state, y = conc, colour = "Puromycin (Treatment2)")) 
mycp

mycp2 <- ggplot() +
  geom_violin(data = dat1, aes(x = state, y = conc, colour = "Puromycin (Treatment1)")) +
  geom_violin(data = dat2, aes(x = state, y = conc, colour = "Puromycin (Treatment2)")) +
  scale_x_discrete(limits = c("untreated", "treated"))
mycp2

Stack the data into a single data frame and set the order by converting treatment to a factor. In your example, the colors and legend are redundant, since you can label the x-axis values to describe each treatment, or change the x-axis title to "Myc Pathway", but the code below in any case shows how to get the ordering.
library(tidyverse)
bind_rows(mydata1, mydata2) %>%
  mutate(treatment = factor(treatment, levels=paste0("Treatment", c(2,1)) %>%
  ggplot(aes(treatment, Myc_List1, colour=treatment)) +
    geom_violin()
Here's a reproducible example:
library(tidyverse)
theme_set(theme_bw(base_size=15))
# Create two separate data frames to start with
d1=iris %>% filter(Species=="setosa")
d2=iris %>% filter(Species=="versicolor") 
bind_rows(d1, d2) %>% 
  mutate(Species = factor(Species, levels=c("versicolor", "setosa"))) %>% 
  ggplot(aes(Species, Petal.Width, colour=Species)) +
    geom_violin()

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With