I am using a loop to perform faceting with ggplot and facet_wrap; I used stat_smooth and stat_cor for statistical analysis and I need to visualise the R coefficient (spearman coefficient) on the plot. In the resulting facets, I would like to have the panels ordered based on those statistical results I am calculating in the plot function itself (from the highest to the lowest R coefficient). e.g.: in facet a: I need to turn panel 1: R = 0.1, panel 2: R= 0.01; panel 3: R= 2 (from left to right on the plot) into panel 3, panel 1, panel 2 (as panel 3's the highest R coefficient resulted from the test and panel 2 the lowest). N.B.: the table I am using for faceting doesn't contain these stats data, I am calculating it in the ggplot function itself in the loop.
Thank you!
Something like this but adding the correlation coefficient as a label and ordering the panels by increasing value of the correlation coefficient:
library(ggplot2)
ggplot(mtcars, aes(disp, mpg)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ x) +
facet_wrap(~cyl)
Created on 2021-10-19 by the reprex package (v2.0.1)