Search code examples
rggplot2ggpmisc

How to position R-squared and equation in Facet mode?


I want to show the linear equation and the R-squared in the each plot in facet mode. This is my code so far.

library("ggplot2")
datos <- read.table("~/Documents/master2/plots/dosis_todos/datos.dat", header=TRUE, quote="\"")
ggplot(datos, aes(x = corriente, y = dosis, colour = cristal)) +    
geom_point() + geom_smooth(method="lm", se=F) + 
facet_wrap(~datos$cristal)

After reading about ggpmisc in this answer, I tried

my.formula <- y ~ x
library("ggpmisc")
ggplot(datos, aes(x = corriente, y = dosis, colour = cristal)) +    
geom_point() + 
geom_smooth(method="lm", se=F, formula=my.formula) +
stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")), formula = my.formula, parse = TRUE) +
facet_wrap(~datos$cristal)

Which kinda works, except that the position of the equation goes down for every plot until disappears...

enter image description here

If I save my plot big enough, I can see all my text in the 9 plots ....going down.

So I guess the question is how to keep fixed the position of the equation and the R-squared information?

Thanks

Ps. Yes, I know N57 has only 3 points :(

Ps. Here is the link to my data


Solution

  • @murpholinox Yes, you are correct, the code in 'ggpmisc' is not smart enough (yet) to detect when aesthetics values like the different colours are unique to each panel. However, it is possible to manually position the equations passing a position in data units to parameters label.y and/or label.x. So, there is a work-around.

    library("ggplot2")
    library("ggpmisc")
    datos <- read.table("datos.dat", header=TRUE, quote="\"")
    my.formula <- y ~ x
    ggplot(datos, aes(x = corriente, y = dosis, colour = cristal)) +
    geom_point() +
    geom_smooth(method="lm", se=F, formula=my.formula) +
    stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
                 formula = my.formula, parse = TRUE, label.y = 0.9) +
    ylim(0, 1) +
    facet_wrap(~datos$cristal)
    

    plot

    It is also possible to pass a vector to label.y and label.x, so that each equation can be manually positioned for each panel.

    ggplot(datos, aes(x = corriente, y = dosis, colour = cristal)) +
    geom_point() +
    geom_smooth(method="lm", se=F, formula=my.formula) +
    stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
                 formula = my.formula, parse = TRUE, 
                 label.y = c(rep(0.9, 6), rep(0.15, 2), 0.9)) +
    ylim(0, 0.95) +
    facet_wrap(~datos$cristal)
    

    enter image description here