之前在文章R语言可视化——ggplot2画回归曲线1中介绍过使用ggplot2中ggplot函数去添加回归曲线的R方方差分析表等。但是ggplot的语法比较复杂相对,里面由一个快速上手的函数qplot函数。今天就做一个qplot函数的添加回归曲线R方和方差分析表的例子。
注:添加R方和方差分析都是来源于ggpmisc
,而非ggplot2
。
library(ggplot2) # 加载底层包
library(ggpmisc) #加载ggpmisc包
数据仍然用文献1中的数据构造方法。
n = 100
set.seed(1)
x <- runif(n, 0, 4)
y <- x^2 - x + rnorm(n, 0, 0.4)
MyClass <- factor((x>0) + (x>1) + (x>2) + (x>3),
labels = c("0-1", "1-2", "2-3", "3-4"))
Data <- data.frame(x = x, y = y, class = MyClass)
head(Data)
x y class
1 1.0620347 0.2251253 1-2
2 1.4884956 0.4823130 1-2
3 2.2914135 3.0956100 2-3
4 3.6328312 9.1128858 3-4
5 0.8067277 0.4172914 0-1
6 3.5935587 10.1122656 3-4
p = qplot(x, y, data=Data, geom= c("point","smooth"),
method= "glm", family= binomial) +theme_bw()
p
p +
stat_smooth(color = "blue", formula = y ~ x,fill = "blue", method = "glm") +
stat_poly_eq(
aes(label = paste(..eq.label.., ..adj.rr.label.., sep = '~~~~~~')),
formula = y ~ x, parse = TRUE,
size = 4, #公式字体大小
label.x = 0.1,
label.y = 0.8) +
stat_fit_tb(method = "lm",
method.args = list(formula = y ~ x),
tb.type = "fit.anova",
tb.vars = c(Effect = "term",
"自由度" = "df",
"均方" = "meansq",
"italic(F值)" = "statistic",
"italic(P值)" = "p.value"),
label.y = 0.7, label.x = 0.05,
size = 4.5,
parse = TRUE
)
以上仅为参考,如由问题欢迎留言讨论。
https://blog.csdn.net/weixin_46111814/article/details/105650257 ↩︎ ↩︎