You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ggplot2绘制ks包输出的KDE双变量核密度估计结果

实现方案

你可以直接提取ks::kde返回对象的内置计算结果,转换为ggplot2支持的长数据框格式后即可绘图,全程不会用到ggplot2原生依赖MASS的KDE接口,完全符合你的使用要求。

前置准备:数据结构转换

首先加载所需包,生成示例KDE结果,再转换为ggplot2可用的数据框:

# 加载依赖包
library(ks)
library(ggplot2)
library(viridis)

# 固定随机种子保证结果可复现
set.seed(123)
data <- cbind(rnorm(100), rnorm(100))
kd <- ks::kde(data)

# 转换为长格式数据框,仅需2行代码
kde_df <- expand.grid(x = kd$eval.points[[1]], y = kd$eval.points[[2]])
kde_df$density <- as.vector(kd$estimate)

1. 等效slice切片图(等高线图)

对应原生plot(kd, display = "slice")的效果:

ggplot(kde_df, aes(x = x, y = y)) +
  geom_contour(aes(z = density, color = after_stat(level)), bins = 20) +
  scale_color_viridis_c() +
  theme_bw() +
  labs(x = "变量1", y = "变量2", color = "密度值")

2. 等效image热力图

对应原生plot(kd, display = "image")的效果:

ggplot(kde_df, aes(x = x, y = y)) +
  geom_raster(aes(fill = density)) +
  # 如需叠加等高线可以加下一行代码
  # geom_contour(color = "white", alpha = 0.3, bins = 10) +
  scale_fill_viridis_c() +
  theme_bw() +
  labs(x = "变量1", y = "变量2", fill = "密度值")

3. 等效persp透视图

ggplot2本身无原生3D渲染能力,可结合rayshader包将2D热力图转换为3D透视图,和原生效果一致:

# 首次使用需先安装:install.packages("rayshader")
library(rayshader)

# 先绘制基础热力图
base_plot <- ggplot(kde_df, aes(x = x, y = y)) +
  geom_raster(aes(fill = density)) +
  scale_fill_viridis_c() +
  theme_void()

# 渲染为3D透视图
plot_gg(base_plot, width = 5, height = 5, scale = 300,
        zoom = 0.7, phi = 30, theta = 30, sunangle = 225)
# 渲染完成后可运行render_snapshot()保存静态图片

内容的提问来源于stack exchange,提问作者3N4N

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:06:10