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

如何用ggplot2将点阵图转换为以value列填充的邻接六边形热力图?

基于ggplot2实现邻接六边形热力图及优化点阵图

方案一:邻接六边形热力图

借助ggforce包的geom_hexagon可以实现规整的邻接六边形网格,每个六边形填充对应value的颜色。代码如下:

library(ggplot2)
library(ggforce)

# 生成原始数据
rows = 1:10; cols = 1:10
grid_data = expand.grid(rows, cols)
colnames(grid_data) <- c("x", "y")
set.seed(123)
grid_data$value = sample(1:100, size = nrow(grid_data), replace = TRUE)

# 绘制六边形热力图
ggplot(grid_data, aes(x = x, y = y, fill = value)) +
  geom_hexagon(size = 0.2, radius = 0.5) +  # radius设为0.5让六边形紧密邻接,size控制边框粗细
  scale_fill_viridis_c(option = "plasma") +  # 可选配色,提升视觉效果
  theme_void()

说明:

  • 若未安装ggforce,先运行install.packages("ggforce")完成安装;
  • 可替换配色方案,比如用scale_fill_gradient(low = "lightblue", high = "darkred")实现渐变效果。

方案二:优化版点阵图(按value着色)

如果不需要严格的六边形,可优化原始点阵图,让点足够大以形成邻接的视觉效果,同时保留按value着色的逻辑:

library(ggplot2)

# 生成原始数据(同前)
rows = 1:10; cols = 1:10
grid_data = expand.grid(rows, cols)
colnames(grid_data) <- c("x", "y")
set.seed(123)
grid_data$value = sample(1:100, size = nrow(grid_data), replace = TRUE)

# 优化后的点阵图
ggplot(grid_data, aes(x = x, y = y, color = value)) +
  geom_point(size = 8, shape = 15) +  # shape=15为正方形点,size设为8让点邻接
  scale_color_viridis_c(option = "plasma") +
  theme_void() +
  guides(color = guide_colorbar(title = "Value"))  # 添加颜色图例明确对应关系

说明:

  • 也可使用shape=16(圆形点),调整size参数适配网格间距;
  • 图例可根据需求选择保留或移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 03:52:34