有没有人知道ggplot2中的panel.lmlineq和panel.text(来自格子)的等价物?

时间:2017-01-19 18:37:47

标签: r ggplot2 correlation lattice lm

我有以下玩具示例,说明我想要实现的目标:

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")

enter image description here

所以,正如你所看到的,我有一个数据框,其中包含我想要绘制的水平(Species)(同时所有),显示其回归线的R平方值以及打印他们的cor()cor.test()输出。优选地,以美学上令人愉悦的方式。

有没有人试图做类似的事情?有没有一种有效的方法呢?

1 个答案:

答案 0 :(得分:4)

tidyverse扩展程序ggplot2的帮助下,我使用ggpmisc 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)

enter image description here