I wanted to plot several regressions equations in different facets using ggplot2...and I think I succeeded thanks to this post.
But geom_text font is ugly, as it copies the same letters several times in the same text zone :
iris <- iris
iris2 <- data.frame(iris, family = c(rep(rep(1:2,25),3)))
iris3 <- data.frame(iris2, group = paste(iris2$Species, iris2$family, sep = "_"))
intercept <- ddply(iris3, .(group), function(x) coefficients(lm(Petal.Length~Petal.Width,x)))
rcarre <- ddply(iris3, .(group), function(x) summary(lm(Petal.Length~Petal.Width,x))$r.squared)
names(rcarre) <- c("group", "R2")
names(intercept) <- c("group", "intercept", "slope")
coefs <- merge(intercept, rcarre)
coefs <- data.frame(coefs,
eq = paste("Y=",round(coefs$intercept,2),"+",round(coefs$slope, 2),"x",", ","R2=",round(coefs$R2,2), sep = ""))
coefs$eq = as.character(coefs$eq)
iris4 <- merge(iris3, coefs)
ggplot(iris4, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
geom_point() +
geom_smooth(method=lm, se=F) +
facet_grid(family~Species) +
geom_text(aes(label=eq, x=1.5, y=6)) +
theme_linedraw()
I tried to use the given solution here but it doesn't work for me
ggplot(iris4, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
geom_point() +
geom_smooth(method=lm, se=F) +
facet_grid(family~Species) +
geom_text(aes(label=iris4$eq, x=1.5, y=6), data = data.frame()) +
theme_linedraw()
With annotate, I have an error message (I understand the problem but I can't solve it)
ggplot(iris4, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
geom_point() +
geom_smooth(method=lm, se=F) +
facet_grid(family~Species) +
annotate("text", x = 1.5, y = 6, label = iris4$eq) +
theme_linedraw()
And if I refer to the coefs table (same length than the facets), the equations don't match anymore
ggplot(iris4, aes(x = Petal.Width, y = Petal.Length, colour = Species)) +
geom_point() +
geom_smooth(method=lm, se=F) +
facet_grid(family~Species) +
annotate("text", x = 1.5, y = 6, label = coefs$eq) +
theme_linedraw()
Anyone would have a solution ?
Thank you very much !