我正在使用

uj5u.com熱心網友回復:
前兩個在 ggplot 中很簡單。這是一個完全可重現的示例:
library(ggplot2)
data <- cbind(rnorm(100), rnorm(100))
d <- ggplot(as.data.frame(data), aes(V1, V2))
scale_color_viridis_c()
theme_bw()
d geom_density2d(aes(colour = after_stat(level)), bins = 5)

d geom_density2d_filled()

編輯
要專門使用 的輸出ks::kde(),我們需要使用 將其資料從矩陣轉換為長格式reshape2::melt,但是在 ggplot 中繪制仍然很容易:
set.seed(1)
data <- cbind(rnorm(100), rnorm(100))
kd <- ks::kde(data)
library(ggplot2)
等高線圖
ggplot(reshape2::melt(kd$estimate))
geom_contour(aes(x = Var1, y = Var2, z = value, color = stat(level)),
bins = 5)
scale_color_viridis_c()
coord_equal()
theme_classic()

填充等高線圖
ggplot(reshape2::melt(kd$estimate))
geom_contour_filled(aes(x = Var1, y = Var2, z = value, fill = stat(level)),
bins = 9)
scale_fill_viridis_d()
coord_equal()
theme_classic()
theme(legend.position = "none")

光柵影像
ggplot(reshape2::melt(kd$estimate))
geom_raster(aes(x = Var1, y = Var2, fill = value))
scale_fill_viridis_c()
coord_equal()
theme_classic()
theme(legend.position = "none")

Created on 2021-11-12 by the reprex package (v2.0.0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/358905.html
