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

如何用R的ggplot绘制deldir剖分瓦片并按面积渐变填充

两种实现Voronoi胞元按面积渐变填充的方法

方法一:直接用deldir包实现面积渐变填充

无需额外转换格式,直接计算每个瓦片面积并映射到渐变颜色:

library(deldir)
set.seed(1)
x <- runif(50)
y <- runif(50)

tesselation <- deldir(x, y)
tiles <- tile.list(tesselation)

# 用鞋带公式计算多边形面积
polygon_area <- function(x_coord, y_coord) {
  abs(0.5 * sum(rev(x_coord)*y_coord - x_coord*rev(y_coord)))
}

# 计算每个瓦片的面积
tile_areas <- sapply(tiles, function(tile) polygon_area(tile$x, tile$y))

# 生成对应面积的渐变颜色
library(scales)
color_palette <- gradient_n_pal(hcl.colors(10, "viridis"))(rescale(tile_areas))

# 绘制带圆形裁剪的渐变填充图
s <- seq(0, 2 * pi, length.out = 3000)
circle <- list(x = 0.5 * (1 + cos(s)),
               y = 0.5 * (1 + sin(s)))

plot(tiles, pch = 19,
     col.pts = "white",
     border = "white",
     fillcol = color_palette,
     clipp = circle)

方法二:导入ggplot2实现更灵活的渐变控制

将deldir生成的瓦片转换为sf格式,结合ggplot2的scale_fill_gradientn实现自定义渐变:

library(deldir)
library(ggplot2)
library(sf)
set.seed(1)
x <- runif(50)
y <- runif(50)

tesselation <- deldir(x, y)
tiles <- tile.list(tesselation)

# 将瓦片转换为sf多边形对象,同时计算面积
tile_sf <- lapply(seq_along(tiles), function(i) {
  current_tile <- tiles[[i]]
  # 创建闭合多边形
  poly <- st_polygon(list(cbind(current_tile$x, current_tile$y)))
  # 计算面积
  tile_area <- st_area(poly)
  # 返回包含属性的sf对象
  st_sf(id = i, center_x = current_tile$x0, center_y = current_tile$y0, area = tile_area, geometry = poly)
}) %>% do.call(rbind, .)

# 创建圆形裁剪区域(圆心(0.5,0.5),半径0.5)
circle_clipper <- st_sfc(st_point(c(0.5, 0.5))) %>% 
  st_buffer(dist = 0.5)

# 裁剪Voronoi瓦片
clipped_tiles <- st_intersection(tile_sf, circle_clipper)

# 用ggplot绘制渐变填充图
ggplot(clipped_tiles) +
  geom_sf(aes(fill = area), color = "white") +
  # 自定义渐变颜色,这里用viridis色系,可替换成其他颜色
  scale_fill_gradientn(colors = hcl.colors(10, "viridis")) +
  theme_void()

说明

  • 方法一适合快速实现,直接基于deldir的plot函数;
  • 方法二更灵活,ggplot2支持更多自定义样式(比如添加色标、调整主题等),适合需要精细化调整的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:36:24