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

如何在R语言多组雷达图中修改数据点填充颜色?

解决方案

b) 将所有数据点填充为白色,避免线条透出

fmsb包的radarchart函数可通过指定点类型和填充色实现需求:

  • 使用pty = 21:这是R中标准的可填充空心圆类型,支持单独设置轮廓色与填充色
  • 设置bg = "white":将点的填充色设为白色,完全覆盖下方线条,同时保留pcol参数指定的轮廓颜色

修改后的完整代码:

set.seed(1)
df2 <- data.frame(rbind(rep(10, 8), rep(0, 8),
                        matrix(sample(0:10, 24,
                                      replace = TRUE),
                               nrow = 3)))
colnames(df2) <- paste("Var", 1:8)

library(fmsb)

# Fill colors
areas <- c(rgb(1, 0, 0, 0.25),
           rgb(0, 1, 0, 0.25),
           rgb(0, 0, 1, 0.25))

radarchart(df2,
           cglty = 1,       # Grid line type
           cglcol = "gray", # Grid line color
           pcol = 2:4,      # 点轮廓/线条颜色
           pty = 21,        # 可填充空心圆点类型
           plwd = 2,        # Line width
           plty = 1,        # Line type
           pfcol = areas,   # Area fill colors
           bg = "white")    # 点填充色设为白色

a) 修改单个数据点的填充颜色(理想方案)

radarchart本身不支持直接设置单个点颜色,需在绘制完雷达图后,手动计算目标点坐标,用points()函数覆盖原有点:

示例代码(修改第2组数据的第3个变量点为红色填充):

set.seed(1)
df2 <- data.frame(rbind(rep(10, 8), rep(0, 8),
                        matrix(sample(0:10, 24,
                                      replace = TRUE),
                               nrow = 3)))
colnames(df2) <- paste("Var", 1:8)

library(fmsb)

# Fill colors
areas <- c(rgb(1, 0, 0, 0.25),
           rgb(0, 1, 0, 0.25),
           rgb(0, 0, 1, 0.25))

# 先绘制基础雷达图
radarchart(df2,
           cglty = 1,
           cglcol = "gray",
           pcol = 2:4,
           pty = 21,
           plwd = 2,
           plty = 1,
           pfcol = areas,
           bg = "white")

# 计算雷达图的角度和坐标
k <- ncol(df2)  # 变量个数
# 角度从顶部(pi/2弧度)开始,顺时针排列所有变量
theta <- seq(pi/2, pi/2 + 2*pi, length.out = k+1)[-1]

# 定义要修改的目标点:第2组数据(df2第4行)、第3个变量(Var3,索引3)
group_idx <- 4
var_idx <- 3

# 归一化数据值(匹配雷达图的坐标缩放)
normalized_val <- (df2[group_idx, var_idx] - df2[2, var_idx]) / 
                  (df2[1, var_idx] - df2[2, var_idx])
# 计算目标点的笛卡尔坐标
x <- normalized_val * cos(theta[var_idx])
y <- normalized_val * sin(theta[var_idx])

# 重新绘制目标点,设置红色填充,保留原轮廓色
points(x, y, pch = 21, bg = "red", col = pcol[2], cex = 1.2)

你可根据需求修改group_idx、var_idx和bg参数,实现任意单个点的颜色自定义。

内容的提问来源于stack exchange,提问作者Betsy S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 17:18:26