I have two questions:
- how to have the same color in geom_text as in the geom_point?
- how to remove legend title?
Assuming the following data set:
library(ggplot2)
library(reshape2)
speed <- c(0, seq(from = 30, to = 330, by = 60))
power1 <- c(75, 85, 88, 85, 94, 92, 95)
power2 <- c(72, 82, 78, 69, 74, 85, 89)
dt <- data.frame(speed=speed, power1=power1, power2=power2)
dt <- melt(data = dt, id.vars = c("speed"))
I'm making the plot with the following code:
p <- ggplot(data = dt, aes(x = speed, y = value, fill = variable)) +
geom_point(aes(color=variable), size = 2) +
stat_smooth(aes(color=variable), method = lm, formula = y ~ poly(x, 2), se = FALSE, size = 1)
p <- p + geom_text(aes(x = 100,
y = 93,
label = lm_eqn(lm(formula = value ~ poly(speed,2),
data = subset(x = dt, subset = variable == "power1")
)
)
),
color = "black",
parse = TRUE) +
geom_text(aes(x = 250,
y = 72,
label = lm_eqn(lm(formula = value ~ poly(speed,2),
data = subset(x = dt, subset = variable == "power2")
)
)
),
color = "black",
parse = TRUE)
p
Help function for the label:
lm_eqn = function(m) {
# from:
# https://stackoverflow.com/questions/7549694/ggplot2-adding-regression-line-equation-and-r2-on-graph
l <- list(a = format(coef(m)[1], digits = 2),
b = format(abs(coef(m)[2]), digits = 2),
c = format(abs(coef(m)[3]), digits = 2),
s1 = ifelse(test = coef(m)[2]>0, yes = "+", no = "-"),
s2 = ifelse(test = coef(m)[3]>0, yes = "+", no = "-"),
r2 = format(summary(m)$r.squared, digits = 3));
eq <- substitute(italic(y) == a~~s1~~b %.% italic(x)^2 ~~s2~~c%.% italic(x)*","~~italic(r)^2~"="~r2,l)
as.character(as.expression(eq));
}
And the plot looks like this:
So, how to:
- change geom_text color to the same as points color?
- remove legend title?