我的数据如下
data <- structure(list(code = 1:12, outcome1 = c(75L, 76L, 77L, 78L,
80L, 82L, 85L, 84L, 78L, 84L, 84L, 75L), outcome2 = c(50L, 55L,
54L, 52L, 56L, 58L, 59L, 54L, 52L, 56L, 56L, 57L), response1 = c(1500L,
1800L, 1789L, 1200L, 1400L, 1900L, 1800L, 1100L, 1450L, 1750L,
1770L, 1000L), response2 = c(100L, 111L, 120L, 140L, 144L, 156L,
147L, 189L, 165L, 154L, 132L, 171L)), class = "data.frame", row.names = c(NA,
-12L))
我有许多结果= 8,响应变量= 22。
我想为所有结果*响应组合创建一系列回归图。是否有快速简便的方法来做到这一点?
例如:结果1 *响应1,结果1 *响应2,结果2 *响应1,依此类推。
这是用于通过response1图创建一个这样的result1的示例代码。
ggplot(data = data, aes(x = outcome1, y = response1)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE)
编辑:我已经考虑过刻面,但是这可能在这里不起作用,因为对于每个结果(x),各种响应(y)都位于不同的单位中。因此,y轴刻度在不同的(y)上无法比较。
答案 0 :(得分:4)
在输入ggplot
之前,始终将数据转换为长格式。然后,我们可以使用facet_grid
创建图:
library(ggplot2)
library(dplyr)
library(tidyr)
data %>%
gather(var1, value1, outcome1:outcome2) %>%
gather(var2, value2, response1:response2) %>%
ggplot(aes(x = value1, y = value2)) +
geom_point(color='blue') +
geom_smooth(method = "lm", se = FALSE) +
facet_grid(var2 ~ var1, scales = "free", switch = "both",
labeller = as_labeller(c(response1 = "response1 (mm)",
response2 = "response2 (kg)",
outcome1 = "outcome1 (index)",
outcome2 = "outcome2 (index)"))) +
labs(title = "Regression Plot Matrix", x = NULL, y = NULL) +
theme_bw() +
theme(strip.placement = "outside",
strip.background = element_blank())
注释:
由于变量可以具有不同的比例,因此我们在scale = "free"
中使用facet_grid
来允许每个轴自由缩放。
switch = "both"
将分面标签更改为另一面
labeller
使我们能够提供命名的矢量并根据需要更改带状标签
strip.placement = "outside"
将条形标签设置在轴刻度之外,而strip.background = element_blank()
则删除灰色条形标签背景(由aosmith启发于this answer)
labs(..., x = NULL, y = NULL)
删除默认的轴标签,有效地将修改后的小平面带状标签视为轴标签
输出:
> data %>%
+ gather(var1, value1, outcome1:outcome2) %>%
+ gather(var2, value2, response1:response2)
code var1 value1 var2 value2
1 1 outcome1 75 response1 1500
2 2 outcome1 76 response1 1800
3 3 outcome1 77 response1 1789
4 4 outcome1 78 response1 1200
5 5 outcome1 80 response1 1400
6 6 outcome1 82 response1 1900
7 7 outcome1 85 response1 1800
8 8 outcome1 84 response1 1100
9 9 outcome1 78 response1 1450
10 10 outcome1 84 response1 1750
11 11 outcome1 84 response1 1770
12 12 outcome1 75 response1 1000
13 1 outcome2 50 response1 1500
14 2 outcome2 55 response1 1800
...