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

在R的ggplot中创建可条件填充的自定义独立轮廓图形

在R中绘制带条件填充的自定义形状并组合展示

核心实现思路

用ggplot2包绘制自定义多边形,通过整理所有形状的顶点坐标数据,结合数值映射实现条件填充,同时统一设置黑色轮廓。以下是完整可运行的示例代码:

步骤1:准备形状坐标与填充数据

先构造7个不同形状的顶点坐标,同时为每个形状分配用于条件填充的数值:

library(ggplot2)

# 定义7个形状的坐标数据
shape_data <- list(
  # 形状1:三角形
  data.frame(
    shape_id = "Shape 1",
    x = c(0, 1, 0.5),
    y = c(0, 0, 1),
    value = 20
  ),
  # 形状2:矩形
  data.frame(
    shape_id = "Shape 2",
    x = c(1.5, 2.5, 2.5, 1.5),
    y = c(0, 0, 1, 1),
    value = 45
  ),
  # 形状3:圆形(用多点模拟)
  data.frame(
    shape_id = "Shape 3",
    x = 3.5 + cos(seq(0, 2*pi, length.out = 50)),
    y = 0.5 + sin(seq(0, 2*pi, length.out = 50)),
    value = 60
  ),
  # 形状4:梯形
  data.frame(
    shape_id = "Shape 4",
    x = c(5, 6.5, 6, 4.5),
    y = c(0, 0, 1, 1),
    value = 15
  ),
  # 形状5:菱形
  data.frame(
    shape_id = "Shape 5",
    x = c(7.5, 8, 7.5, 7),
    y = c(0.5, 1, 0.5, 0),
    value = 75
  ),
  # 形状6:五边形
  data.frame(
    shape_id = "Shape 6",
    x = 9 + cos(seq(0, 2*pi, length.out = 5)[-5]),
    y = 0.5 + sin(seq(0, 2*pi, length.out = 5)[-5]),
    value = 30
  ),
  # 形状7:不规则多边形
  data.frame(
    shape_id = "Shape 7",
    x = c(10.5, 12, 11.8, 10.8, 10.2),
    y = c(0, 0.3, 1, 0.7, 0.2),
    value = 50
  )
)

# 合并为单个数据框
shape_df <- do.call(rbind, shape_data)

步骤2:绘制带条件填充的图形

根据数值实现条件填充,这里示例用渐变填充,也可改为离散分类填充:

# 绘制图形
ggplot(shape_df, aes(x = x, y = y, group = shape_id, fill = value)) +
  geom_polygon(color = "black", linewidth = 1) + # 黑色轮廓
  # 条件填充:渐变示例(可替换为离散分类)
  scale_fill_gradient(low = "#e6f7ff", high = "#ff4d4d", 
                      breaks = c(20, 40, 60, 80),
                      name = "填充数值") +
  theme_void() + # 去除多余坐标轴与背景
  theme(legend.position = "bottom")

条件填充的自定义调整

如果需要按数值区间分类填充,比如数值>50用红色,≤50用蓝色,可修改如下:

# 添加分类列
shape_df$fill_group <- ifelse(shape_df$value > 50, "高值", "低值")

ggplot(shape_df, aes(x = x, y = y, group = shape_id, fill = fill_group)) +
  geom_polygon(color = "black", linewidth = 1) +
  scale_fill_manual(values = c("高值" = "#ff4d4d", "低值" = "#4da6ff"),
                    name = "填充分组") +
  theme_void() +
  theme(legend.position = "bottom")

关键点说明

  • 每个形状的坐标需要按顺时针或逆时针顺序排列,否则geom_polygon可能绘制出异常图形。
  • 可通过调整x、y坐标的位置控制形状在画布上的布局,避免重叠。
  • linewidth参数可调整黑色轮廓的粗细,按需修改即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:07:27