gpt4 book ai didi

r - "Quick"带有 ggplot 的散点图图例?

转载 作者:行者123 更新时间:2023-12-01 08:17:11 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:




9年前关闭。




Possible Duplicate:
ggplot2: Adding Regression Line Equation and R2 on graph



我在散点图中绘制数据
ggplot(work.rootsfnp.h1, aes(x=fnpltrfac, y=rootsscore, group=1)) + 
geom_smooth(method=lm, se = F) + geom_point(shape=1)

是否有一种“快速”方法可以添加包含最佳拟合线公式和相关系数的基本图例?

最佳答案

不快,但可能:

首先,使用 lm 拟合模型

model <- lm(mpg ~ wt + factor(cyl), data=mtcars)

然后提取系数和R^2,并为每个构造表达式
x <- coef(model)
intercept <- signif(x[1], 3)
terms <- paste(signif(x[-1], 3), names(x[-1]), sep="*", collapse= " + ")
e1 <- paste(intercept, terms, collapse = " + ")
e2 <- paste("R^2 = ", round(summary(model)$r.squared, 3))

最后,用 ggplot 绘图并使用 annotate放置标签。
ggplot(mtcars, aes(x=wt, y=mpg)) + 
geom_point() +
geom_smooth(method=lm) +
annotate("text", label=e1, x=max(mtcars$wt), y=max(mtcars$mpg),
hjust=1, size=3, vjust=0) +
annotate("text", label=e2, x=max(mtcars$wt), y=max(mtcars$mpg),
hjust=1, size=3, vjust=1)

enter image description here

关于r - "Quick"带有 ggplot 的散点图图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8313619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com