【发布时间】:2018-08-15 11:12:25
【问题描述】:
我想显示一个输出变量和多个输入变量之间的所有相关性。
我准确地说:
- 我不需要明确计算相关系数
- 我不需要所有变量之间的完整相关矩阵:我对显示输入变量之间的相关图不感兴趣。
我可以使用循环或apply 调用,但我想知道使用ggplot2 的facet 函数是否有更好、更优雅的解决方案。
这是一个简化的例子。我想分面三个可能的相关图。
library(ggplot2)
# data
output <- c(3, 5, 8, 9, 12, 13)
input_1 <- c(1, 3, 4, 6, 8, 11)
input_2 <- c(3, 8, 2, 5, 11, 1)
input_3 <- c(14, 8, 6, 4, 2, 1)
mydf <- data.frame(output, input_1, input_2, input_3)
# First Correlation plot
ggplot(data = mydf, aes(x = input_3, y = output)) +
geom_point() +
geom_smooth(method = "lm")
# Second correlation plot
ggplot(data = mydf, aes(x = input_2, y = output)) +
geom_point() +
geom_smooth(method = "lm")
# Third correlation plot
ggplot(data = mydf, aes(x = input_3, y = output)) +
geom_point() +
geom_smooth(method = "lm")
【问题讨论】:
-
您在谈论显示相关性,但绘制
geom_point和geom_smooth。那么你想展示什么?您的示例中没有计算相关性的代码。 -
不过,这是很常见的长/宽数据格式问题。您只需要
melt您的数据:ggplot(reshape2::melt(mydf, "output"), aes(value, output)) + geom_point() + facet_wrap(~ variable)
标签: r ggplot2 correlation