有谁知道 ggplot2 中 panel.lmlineq 和 panel.text (来自 lattice)的等价物?
Does anyone know the equivalent of panel.lmlineq and panel.text (from lattice) in ggplot2?
我有以下我想要实现的玩具示例:
library ("lattice")
library ("latticeExtra")
data (iris)
xyplot(Sepal.Width ~ Sepal.Length | Species, data = iris, panel = function(x, y, ...) {
panel.xyplot(x, y, ...)
panel.lmlineq(x, y, adj = c(1,0),
lty = 1,col.text='red', pos= 4,
col.line = "blue", digits = 1,r.squared =TRUE)
panel.text(7, 4, round(cor(x, y),3), font=2, adj=c(0.5,-0.6))
panel.text(7, 4, round(cor.test(x,y)$p.value, 3), font=1, adj=c(0.5,0.6))},
xlab = "Sepal.Length", ylab = "Sepal_Width")
因此,如您所见,我有一个数据框,其中包含水平 (Species
),我想绘制(所有同时)显示其回归线与 R 平方值并打印它们的 cor()
和 cor.test()
输出。优选地,以美观的方式。
有没有人试过做类似的事情?有没有有效的方法来做到这一点?
在 ggplot2
扩展程序 ggpmisc
的帮助下,我使用 tidyverse
workflow 做这样的事情。有很大的定制空间,您可以根据需要最小化或简化内容。
library(tidyverse)
library(broom)
library(ggpmisc)
analysis <- iris %>%
group_by(Species) %>%
nest() %>%
mutate(model = map(data, ~lm(Sepal.Length ~ Sepal.Width, data = .)),
cor = map(data, ~tidy(cor.test(.x$Sepal.Length, .x$Sepal.Width), 3)))
stats <- analysis %>%
unnest(cor)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(shape = 21) +
geom_text(data = stats, aes(label = sprintf("r = %s", round(estimate, 3)), x = 7, y = 4)) +
geom_text(data = stats, aes(label = sprintf("p = %s", round(p.value, 3)), x = 7, y = 3.8)) +
geom_smooth(method = "lm", formula = y ~ x) +
stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")),
formula = y ~ x,
parse = TRUE) +
facet_wrap(~Species)
我有以下我想要实现的玩具示例:
library ("lattice")
library ("latticeExtra")
data (iris)
xyplot(Sepal.Width ~ Sepal.Length | Species, data = iris, panel = function(x, y, ...) {
panel.xyplot(x, y, ...)
panel.lmlineq(x, y, adj = c(1,0),
lty = 1,col.text='red', pos= 4,
col.line = "blue", digits = 1,r.squared =TRUE)
panel.text(7, 4, round(cor(x, y),3), font=2, adj=c(0.5,-0.6))
panel.text(7, 4, round(cor.test(x,y)$p.value, 3), font=1, adj=c(0.5,0.6))},
xlab = "Sepal.Length", ylab = "Sepal_Width")
因此,如您所见,我有一个数据框,其中包含水平 (Species
),我想绘制(所有同时)显示其回归线与 R 平方值并打印它们的 cor()
和 cor.test()
输出。优选地,以美观的方式。
有没有人试过做类似的事情?有没有有效的方法来做到这一点?
在 ggplot2
扩展程序 ggpmisc
的帮助下,我使用 tidyverse
workflow 做这样的事情。有很大的定制空间,您可以根据需要最小化或简化内容。
library(tidyverse)
library(broom)
library(ggpmisc)
analysis <- iris %>%
group_by(Species) %>%
nest() %>%
mutate(model = map(data, ~lm(Sepal.Length ~ Sepal.Width, data = .)),
cor = map(data, ~tidy(cor.test(.x$Sepal.Length, .x$Sepal.Width), 3)))
stats <- analysis %>%
unnest(cor)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(shape = 21) +
geom_text(data = stats, aes(label = sprintf("r = %s", round(estimate, 3)), x = 7, y = 4)) +
geom_text(data = stats, aes(label = sprintf("p = %s", round(p.value, 3)), x = 7, y = 3.8)) +
geom_smooth(method = "lm", formula = y ~ x) +
stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")),
formula = y ~ x,
parse = TRUE) +
facet_wrap(~Species)