# Factor() to order facets in ggplot2 by statistical correlation obtained in table

Hello!

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).

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.

Here is my code. Thank you in advance!

[/for (n in colnames(spearmannn)){

imp.prot ← rownames(spearmannn[order(spearmannn[, n], decreasing = T),][c(1:10,76:85),])
imp.prot.plot ← table_for_statistics[imp.prot,]
factor(imp.prot.plot\$protein, levels = unique(imp.prot))

print(ggplot(table_for_statistics[table_for_statistics\$protein %in% imp.prot,], aes(x = table_for_statistics[table_for_statistics\$protein %in% imp.prot, n], y= measurement))+ geom_beeswarm(aes(col= iss_group), shape=21, size=2,cex = 0.5) + facet_wrap(~protein, scales = “free_y”, ncol = 5) + labs(x=n)+
stat_smooth(method = lm, formula = ‘y~x’) +
stat_cor(method = “spearman”, label.x.npc = 0.2, label.y.npc = 1, size = 3.5))
}

P.S. The expression levels of the proteins are obtained from 415 patiens, hence the name of each protein repeated multiple times in table_for_statistics.

I am by no means an expert and probably because I am somewhat new to R and don’t know my biochem well I don’t have a great grasp on what you are trying to accomplish. However, this is what I understand you to be attempting to do:
Order a data frame based on information in another data frame then create a graph from that information. If this is your intention, then I’d think the process would be to create a temporary data frame by joining the two tables, ordering that, then plotting it.

Other than that you seem to think that the problem is in your factor function, therefore I’m linking the rdocumentation link for the factor function which your code does not seem to perfectly match maybe?: R Documentation for Factor Function

I’m happy to try and talk it out with you, maybe doing so will help you better understand the problem and find the answer?