title: Factor() to order facets in ggplot2 by statistical correlation obtained in table
body: <p>I displayed n proteins on a ggplot facets using a for loop, as I have to plot the expression levels of these proteins against more than one clinical variable (numerical). The proteins I chose to plot have been selected from a wider table of proteins and have been filtered for the significance of their correlations (a spearman test was originally performed to obtain the correlation of the protein expression with the clinical variables).</p>
  <p>I now would like to order the facets with the proteins on the plot created by their correlation (order: ascending).
  I tried to use the factor() function, but something must be wrong.</p>
  <p>Here is my code and I am going to attach the tables as screens (they're too long to be copied here as code).<a href="https://i.stack.imgur.com/toxTJ.png" rel="nofollow noreferrer">table_for_statistics &amp; spearmannn tables</a> Thank you in advance!</p>
  <pre><code>for (n in colnames(spearmannn)){
     
     
  imp.prot &lt;- rownames(spearmannn[order(spearmannn[, n], decreasing = T),][c(1:10,76:85),])
  imp.prot.plot &lt;- table_for_statistics[imp.prot,] 
   factor(imp.prot.plot$protein, levels = unique(n))
  
   print(ggplot(table_for_statistics[table_for_statistics$protein %in% imp.prot.plot,], aes(x = table_for_statistics[table_for_statistics$protein %in% imp.prot.plot, n], y= measurement))+ geom_beeswarm(aes(col= `iss_group`, fill= `inf`), shape=21, size=2,cex = 0.5) + 
     facet_wrap(~protein, scales = &quot;free_y&quot;, ncol = 5) + labs(x=n)+ scale_fill_manual(values = c(&quot;darkgreen&quot;, &quot;darkred&quot;), name = &quot;Infection&quot;, labels = c(&quot;No Infection&quot;, &quot;Infection&quot;)) +
     stat_smooth(method = lm, formula = 'y~x') +
    stat_cor(method = &quot;spearman&quot;, label.x.npc = 0.2, label.y.npc = 1, size = 3.5)) 
   
  } 
  
  </code></pre>