R:将一个变量与其余变量配对 [英] R: pairs plot of one variable with the rest of the variables

查看:16
本文介绍了R:将一个变量与其余变量配对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用我的"True"变量对和所有其他变量(People变量)生成一个相关图。我非常肯定有人在某个地方提到过这一点,但我发现的解决方案对我不起作用。

library(ggplot2)
set.seed(0)

dt = data.frame(matrix(rnorm(120, 100, 5), ncol = 6) )
colnames(dt) = c('Salary', paste0('People', 1:5))
ggplot(dt, aes(x=Salary, y=value)) +
  geom_point() + 
  facet_grid(.~Salary)
错误:列y必须是一维原子向量或列表。

我知道其中一个解决方案是写出y中的所有变量--我试图避免这样做,因为我的真实数据有15列。

我也不完全确定ggploy中的"值"、"变量"指的是什么。我在演示代码时经常看到它们。

如有任何建议,欢迎光临!

推荐答案

您希望使用tidyr::gather()将数据从wide转换为long格式。以下是使用tidyverse框架中的包的解决方案

library(tidyr)
library(ggplot2)
theme_set(theme_bw(base_size = 14))

set.seed(0)
dt = data.frame(matrix(rnorm(120, 100, 5), ncol = 6) )
colnames(dt) = c('Salary', paste0('People', 1:5))

### convert data frame from wide to long format
dt_long <- gather(dt, key, value, -Salary)
head(dt_long)
#>      Salary     key     value
#> 1 106.31477 People1  98.87866
#> 2  98.36883 People1 101.88698
#> 3 106.64900 People1 100.66668
#> 4 106.36215 People1 104.02095
#> 5 102.07321 People1  99.71447
#> 6  92.30025 People1 102.51804

### plot
ggplot(dt_long, aes(x = Salary, y = value)) +
  geom_point() +
  facet_grid(. ~ key) 

### if you want to add regression lines
library(ggpmisc)

# define regression formula
formula1 <- y ~ x

ggplot(dt_long, aes(x = Salary, y = value)) +
  geom_point() +
  facet_grid(. ~ key) +
  geom_smooth(method = 'lm', se = TRUE) +
  stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~")), 
               label.x.npc = "left", label.y.npc = "top",
               formula = formula1, parse = TRUE, size = 3) +
  coord_equal()

### if you also want ggpairs() from the GGally package
library(GGally)
ggpairs(dt)

reprex package(v0.2.1.9000)于2019-02-28创建

这篇关于R:将一个变量与其余变量配对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆