首页 文章

使用ggplot2在输出变量和多个输入变量之间绘制相关关系图

提问于
浏览
0

我想显示输出变量和多个输入变量之间的所有相关性 .

我确切地说:

  • 我不需要明确地计算相关系数

  • 我对显示输入变量之间的相关图不感兴趣 .

我可以使用循环或 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")

1 回答

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

相关问题