1

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 !

Community
  • 1
  • 1
L.Garcia
  • 13
  • 2

1 Answers1

0

The problem is that ggplot is printing the text for every row in the data. YOu can stop this by only giving it a single row for each label. Here I do this with dplyr::distinct but there would be other ways

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), data = dplyr::distinct(iris4, eq, .keep_all = TRUE)) +
  theme_linedraw() 
Richard Telford
  • 9,558
  • 6
  • 38
  • 51
  • _The problem is that ggplot is printing the text for every row in the data_ : I knew this (I read it on other posts), but I couldn't find a way to solve that...your answer is exactly what I needed ! Thanks a lot @RichardTelford – L.Garcia Nov 30 '16 at 14:03