在 R 编程中创建散点图的绘图矩阵——pairs()函数
R语言中的pairs()函数 用于返回一个绘图矩阵,由每个数据框对应的散点图组成。
R – 创建散点图矩阵
Syntax: pairs(data)
Parameters:
- data: It is defined as value of pairs Plot.
Returns: Color, Labels, Panels, and by Group in pairs plot.
在 R 中创建散点图的绘图矩阵
示例 1: R 的基本示例——pairs()函数
R
# Set seed for reproducibility
set.seed(425340)
# Sample size of 800
N <- 800
# Create variable
x1 <- rnorm(N)
# Create correlated variable
x2 <- x1 + rnorm(N, 0, 4)
# Create another correlated variable
x3 <- 2 * x1 - x2 + rnorm(N, 0, 3)
data <- data.frame(x1, x2, x3)
pairs(data)
R
# Set seed for reproducibility
set.seed(425340)
# Sample size of 800
N <- 800
# Create variable
x1 <- rnorm(N)
# Create correlated variable
x2 <- x1 + rnorm(N, 0, 4)
# Create another correlated variable
x3 <- 2 * x1 - x2 + rnorm(N, 0, 3)
data <- data.frame(x1, x2, x3)
pairs(~ x1 + x3, data = data)
R
# Set seed for reproducibility
set.seed(425340)
# Sample size of 800
N <- 800
# Create variable
x1 <- rnorm(N)
# Create correlated variable
x2 <- x1 + rnorm(N, 0, 4)
# Create another correlated variable
x3 <- 2 * x1 - x2 + rnorm(N, 0, 3)
data <- data.frame(x1, x2, x3)
pairs(~ x1 + x2 + x3, data = data)
pairs(~ x1 + x3, data = data)
pairs(data[, 1:3],
col = "darkgreen", # Change color
pch = 18, # Change shape of points
# Change labels of diagonal
labels = c("var1", "var2", "var3"),
main = " pairs plot in R")
输出:
在这里,在上面的例子中,对角线显示了三个数值变量的名称。第一行的中间图显示了 x1 和 x2 之间的关系,而第一行的右图显示了 x1 和 x3 之间的关系,依此类推。
示例 2:另一个选择对变量的示例 Plot
R
# Set seed for reproducibility
set.seed(425340)
# Sample size of 800
N <- 800
# Create variable
x1 <- rnorm(N)
# Create correlated variable
x2 <- x1 + rnorm(N, 0, 4)
# Create another correlated variable
x3 <- 2 * x1 - x2 + rnorm(N, 0, 3)
data <- data.frame(x1, x2, x3)
pairs(~ x1 + x3, data = data)
输出:
示例 3:另一个实现修改颜色、点形状、标签和标题的示例
R
# Set seed for reproducibility
set.seed(425340)
# Sample size of 800
N <- 800
# Create variable
x1 <- rnorm(N)
# Create correlated variable
x2 <- x1 + rnorm(N, 0, 4)
# Create another correlated variable
x3 <- 2 * x1 - x2 + rnorm(N, 0, 3)
data <- data.frame(x1, x2, x3)
pairs(~ x1 + x2 + x3, data = data)
pairs(~ x1 + x3, data = data)
pairs(data[, 1:3],
col = "darkgreen", # Change color
pch = 18, # Change shape of points
# Change labels of diagonal
labels = c("var1", "var2", "var3"),
main = " pairs plot in R")
输出: