기본 함수인 pairs로 상관관계를 시각화한다. 데이터는 mtcars data에서 수치형 데이터인 mpg, disp, hp, drat, wt,qsec를 쓴다. cyl을 그룹으로 활용한다.
# 샘플 데이터
data <- mtcars[, c(1,3,4,5,6,7)]
group <- as.factor(mtcars[, c(2)])
# Plot correlation matrix
pairs(data,
pch = 21, bg = c("red", "green3", "blue")[group],
main = "mtcars data by cyl",
panel = panel.smooth)pysch 패키지는 R에서 상관관계 도표를 생성하는 두 가지 기능을 제공합니다. pairs.panel 기능은 pairs의 확장으로 회귀선, 히스토그램, 신뢰 구간 등을 쉽게 추가하고 여러 추가 인수를 사용자 정의할 수 있습니다.
# install.packages("psych")
library(psych)
# pairs.panels(data)
pairs.panels(data,
smooth = TRUE, # If TRUE, draws loess smooths
scale = TRUE, # If TRUE, scales the correlation text font
density = TRUE, # If TRUE, adds density plots and histograms
ellipses = TRUE, # If TRUE, draws ellipses
method = "pearson", # Correlation method (also "pearson" or spearman" or "kendall")
bg=c("red","yellow","blue")[group], #to show color grouping
pch = 21, # pch symbol
lm = FALSE, # If TRUE, plots linear fit rather than the LOESS (smoothed) fit
cor = TRUE, # If TRUE, reports correlations
jiggle = TRUE, # If TRUE, data points are jittered
factor = 2, # factor for jittering (1-5)
hist.col = "light green", # Histograms color
stars = TRUE, # If TRUE, adds significance level with stars
ci = TRUE, # If TRUE, adds confidence intervals
main="mtcars data by cyl")corrplot 패키지는 단일 함수로 다양한 상관 관계도를 생성할 수 있는 매우 유연한 패키지입니다. main 함수의 가장 일반적인 인수는 아래에 설명되어 있지만 자세한 내용은 ?corrplot 을 호출하는 것이 좋습니다. 이 함수의 경우 data 대신 상관 행렬, 즉 cor(data)를 전달해야 합니다.
## corrplot 0.92 loaded
corrplot(cor(data), # Correlation matrix
method = "shade", # Correlation plot method
type = "full", # Correlation plot style (also "upper" and "lower")
diag = TRUE, # If TRUE (default), adds the diagonal
tl.col = "black", # Labels color
bg = "white", # Background color
title = "", # Main title
col = NULL) # Color palette
par(mfrow = c(2, 3))
# Circles
corrplot(cor(data), method = "circle",
title = "method = 'circle'",
tl.pos = "n", mar = c(2, 1, 3, 1))
# Squares
corrplot(cor(data), method = "square",
title = "method = 'square'",
tl.pos = "n", mar = c(2, 1, 3, 1))
# Ellipses
corrplot(cor(data), method = "ellipse",
title = "method = 'ellipse'",
tl.pos = "n", mar = c(2, 1, 3, 1))
# Correlations
corrplot(cor(data), method = "number",
title = "method = 'number'",
tl.pos = "n", mar = c(2, 1, 3, 1))
# Pie charts
corrplot(cor(data), method = "pie",
title = "method = 'pie'",
tl.pos = "n", mar = c(2, 1, 3, 1))
# Colors
corrplot(cor(data), method = "color",
title = "method = 'color'",
tl.pos = "n", mar = c(2, 1, 3, 1)) 패키지의 corrplot.mixed 기능을 사용하면 혼합 방법으로 상관 관계도를 그릴 수 있습니다. 이 경우 원하는 값을 하위(대각선 아래) 인수와 상위(대각선 위) 인수로 설정하는 상관관계 도표 방법을 혼합할 수 있습니다.