UPDATE: 2022-10-28 19:16:44

3Dグラフ

library(plot3D)
y <- x <- seq(-10, 10, length=60)
f <- function(x, y) x^2 + y^2
z <- outer(x, y, f)
persp3D(
  x = x,
  y = y,
  z = z,
  color.palette = heat.colors,
  phi = 35,
  theta = 200,
  main = "3-D perspective")

回帰平面

# rglパッケージは下記のxquartzが必要なので先にインストール
# https://www.xquartz.org/
library(rgl)

# scatter3d(x = iris$Sepal.Width, y = iris$Sepal.Length, z = iris$Petal.Width, groups = iris$Species)と同じ
# scatter3d(formula = Sepal.Length ~ Sepal.Width + Petal.Width | Species, 
#           data = iris,
#           surface.col = c("#999999", "#E69F00", "#56B4E9"),
#           grid.lines = 50)

ベクトル場

# Function: y = x1^2 + x2^2
df <- function(x1, x2){
  # First derivative
  res <- c(2*x1, 2*x2)
  return(res)
}

n <- 10
grid <- expand.grid(seq(-n, n), seq(-n, n))
plot(0, 0, 
     xlim = c(-n, n)*1.3,
     ylim = c(-n, n)*1.3,
     type = "n", xlab = "x1", ylab = "x2")

for(i in 1:nrow(grid)) {
  direction <- df(x1 = grid[i, 1], x2 = grid[i, 2]) * 0.03
  arrows(grid[i, 1],
         grid[i, 2],
         grid[i, 1] + direction[1],
         grid[i, 2] + direction[2],
         length = 0.05,
         )
}

3D同時確率密度関数プロット

library(tidyverse)
library(rayshader)

## geom_function()で簡単に確率密度をプロットできる
ggplot() +
  geom_function(fun=df, args=list(df1=1,df2=1), color="green") +
  geom_function(fun=df, args=list(df1=3,df2=10), color="red") +
  geom_function(fun=df, args=list(df1=10,df2=3), color="blue") +
  xlim(0,5) + 
  theme_classic()

probx <- c(4,3,2,1,1,1)/12
proby <- c(1,1,3,5)/10

# ggplot() +
#   geom_col(aes(x=1:6,y=probx)) +
#   labs(x = "X", y = "P(X)", title="Xの出目とその確率") +
#   theme_classic()

datx <- tibble(x=1:6,px=probx)
daty <- tibble(y=1:4,py=proby)

datxy <- expand_grid(x=1:6,y=1:4) %>% 
  left_join(datx,by="x") %>% 
  left_join(daty,by="y") %>% 
  mutate(pxy = px*py) 

gg <- ggplot(datxy) +
  geom_tile(aes(x = x, y = y, fill=pxy)) +
  labs(x="X", y="Y",title="XとYの同時確率") +
  scale_fill_continuous(name="P(X)P(Y)", type = "viridis") +
  theme_classic()

rayshader::plot_gg(gg)