我想使用ggplot2在不同的方面绘制几个回归方程......我认为我成功归功于this post。
但是geom_text字体很难看,因为它在同一个文本区域中多次复制相同的字母:
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()
我尝试使用给定的解决方案here,但它对我不起作用
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()
使用注释,我有一条错误消息(我理解问题,但我无法解决)
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()
如果我引用coefs表(长度比facet长),则方程式不再匹配
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()
任何人都有解决方案吗?
非常感谢!
答案 0 :(得分:0)
问题是ggplot正在为数据中的每一行打印文本。你可以通过只给每个标签一行来阻止它。在这里,我使用dplyr::distinct
执行此操作,但还有其他方法
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()