R 如何在图形上固定回归线方程的标签(使用ggplot2)
当我在rstudio中运行下面的代码时(见下文),除了线性回归直线方程之外,一切看起来都很好。 不是得到y=3.142x-4.751,而是得到y=c(3.142)xc(-4.751) 我能做些什么来解决这个问题? 事先非常感谢R 如何在图形上固定回归线方程的标签(使用ggplot2),r,ggplot2,graph,rstudio,R,Ggplot2,Graph,Rstudio,当我在rstudio中运行下面的代码时(见下文),除了线性回归直线方程之外,一切看起来都很好。 不是得到y=3.142x-4.751,而是得到y=c(3.142)xc(-4.751) 我能做些什么来解决这个问题? 事先非常感谢 set.seed(3L) library(ggplot2) df <- data.frame(x = c(1:100)) df$y <- 2 + 3 * df$x + rnorm(100, sd = 40) lm_eqn <- function(df)
set.seed(3L)
library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
lm_eqn <- function(df){
# browser()
m <- lm(y ~ x, df)
a <- coef(m)[1]
a <- ifelse(sign(a) >= 0,
paste0(" + ", format(a, digits = 4)),
paste0(" - ", format(-a, digits = 4)) )
eq1 <- substitute( paste( italic(y) == b, italic(x), a ),
list(a = a,
b = format(coef(m)[2], digits=4)))
eq2 <- substitute( paste( italic(R)^2 == r2 ),
list(r2 = format(summary(m)$r.squared, digits = 3)))
c( as.character(as.expression(eq1)), as.character(as.expression(eq2)))
}
labels <- lm_eqn(df)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se=FALSE, color="red", formula = y ~ x) +
geom_point() +
geom_text(x = 75, y = 90, label = labels[1], parse = TRUE, check_overlap = TRUE ) +
geom_text(x = 75, y = 70, label = labels[2], parse = TRUE, check_overlap = TRUE )
print(p)
set.seed(3L)
图书馆(GG2)
df在函数lm_eqn
中,format
函数给出命名向量。通过删除名称,您可以按如下方式解决问题:
set.seed(3L)
library(ggplot2)
df <- data.frame(x = c(1:100))
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
lm_eqn <- function(df){
# browser()
m <- lm(y ~ x, df)
a <- coef(m)[1]
a <- ifelse(sign(a) >= 0,
paste0(" + ", format(a, digits = 4)),
paste0(" - ", format(-a, digits = 4)) )
b <- format(coef(m)[2], digits=4)
names(a) <- names(b) <-NULL
eq1 <- substitute( paste( italic(y) == b, italic(x), a ),
list(a = a,
b = b))
eq2 <- substitute( paste( italic(R)^2 == r2 ),
list(r2 = format(summary(m)$r.squared, digits = 3)))
c( as.character(as.expression(eq1)), as.character(as.expression(eq2)))
}
labels <- lm_eqn(df)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se=FALSE, color="red", formula = y ~ x) +
geom_point() +
geom_text(x = 75, y = 90, label = labels[1], parse = TRUE, check_overlap = TRUE ) +
geom_text(x = 75, y = 70, label = labels[2], parse = TRUE, check_overlap = TRUE )
print(p)
set.seed(3L)
图书馆(GG2)
df这个怎么样:也看看这些:&谢谢你#Jrakru56的链接!谢谢董先生的链接!第一个事实上帮助了我解决了我在显示线性回归线方程时遇到的一些其他问题。