【问题标题】:Facet correlation plots between an output variable and multiple input variables with ggplot2带有ggplot2的输出变量和多个输入变量之间的方面相关图
【发布时间】: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_pointgeom_smooth。那么你想展示什么?您的示例中没有计算相关性的代码。
  • 不过,这是很常见的长/宽数据格式问题。您只需要melt您的数据:ggplot(reshape2::melt(mydf, "output"), aes(value, output)) + geom_point() + facet_wrap(~ variable)

标签: r ggplot2 correlation


【解决方案1】:

有了上面的评论(感谢@PoGibas),我用下面的代码解决了。

library(ggplot2)
library(tidyr)

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

# Change data format
mydf2 <- gather(mydf, key = "key", value = "input", -output)

# Correlation plots between the output and the input variables
ggplot(mydf2, aes(input, output)) +
  geom_point() +
  geom_smooth(method = "lm") +
  facet_wrap(~ key)

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2017-09-28
    • 2015-06-12
    相关资源
    最近更新 更多