任意の相関係数の散布図を描く

任意の相関係数をもつ散布図を描くコード。

library(tidyverse)
## ─ Attaching packages ──────────────── tidyverse 1.2.1 ─
## ✔ ggplot2 3.0.0     ✔ purrr   0.2.5
## ✔ tibble  1.4.2     ✔ dplyr   0.7.6
## ✔ tidyr   0.8.1     ✔ stringr 1.3.1
## ✔ readr   1.1.1     ✔ forcats 0.3.0
## ─ Conflicts ───────────────── tidyverse_conflicts() ─
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
# マカーの呪文
old = theme_set(theme_gray(base_family = "HiraKakuProN-W3"))
set.seed(20180524)
# 散布図 -----------------------------------------
library(MASS)
## 
##  次のパッケージを付け加えます: 'MASS'
##  以下のオブジェクトは 'package:dplyr' からマスクされています: 
## 
##      select
N <- 200
rho <- 0.8
mu <- c(165, 26)
sd1 <- 10
sd2 <- 2
cov <- matrix(ncol = 2, nrow = 2)
cov[1, 1] <- sd1^2
cov[2, 2] <- sd2^2
cov[1, 2] <- sd1 * sd2 * rho
cov[2, 1] <- sd1 * sd2 * rho
df <- mvrnorm(N, mu, cov, empirical = TRUE)
tg <- 10
df %>% transform() %>% ggplot(aes(x = X1, y = X2)) + geom_point() + 
  xlim(140, 190) + ylim(22, 30) + xlab("身長") + ylab("靴のサイズ") + 
  geom_segment(x = df[tg, 1], xend = df[tg, 1], y = df[tg, 
    2], yend = 0, lty = 2, color = "blue") + geom_segment(x = df[tg, 
  1], xend = 0, y = df[tg, 2], yend = df[tg, 2], lty = 2, colour = "blue")
## Warning: Removed 9 rows containing missing values (geom_point).

Share