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

R语言fmsb包绘制RadarChart图形异常的原因排查

问题原因及解决方案

核心问题

你的雷达图异常主要有两个原因:

1. 未满足fmsb包的雷达图数据格式要求

fmsb::radarchart() 强制要求输入的数据框第一行是各变量的最大值,第二行是各变量的最小值,后续行才是需要绘制的观测数据。你的原始数据直接使用了4个体重类别的数据行,没有添加max/min行,导致函数错误识别坐标轴范围,图形出现扭曲。

2. 循环中数据传入错误

原循环里每次都传入 df[c(1,2,3,4),],也就是全部4行数据,导致每次绘制的雷达图都叠加了4个体重类别的图形,而不是单独显示当前循环对应的类别。

修正后的代码

第一步:处理数据集,添加max/min行

library(fmsb)
library(scales)

# 构建原始数据集
df <- data.frame(
  NORTHEAST = c(8914.424, 11151.782, 10818.594, 16606.763),
  NORTHWEST = c(9223.351, 10032.507, 11503.929, 14198.111),
  SOUTHEAST = c(0.00, 13286.81, 10846.20, 16139.57),
  SOUTHWEST = c(7778.771, 7246.518, 10786.970, 14752.032)
)
rownames(df) <- c("UNDERWEIGHT", "NORMALWEIGHT", "OVERWEIGHT", "OBESE")

# 添加max和min行到数据框顶部(fmsb要求的格式)
df_fmsb <- rbind(
  apply(df, 2, max),  # 各列最大值
  apply(df, 2, min),  # 各列最小值
  df
)
rownames(df_fmsb)[1:2] <- c("max", "min")

第二步:修正自定义函数与循环逻辑

create_beautiful_radarchart <- function(data, color = "#800000", 
                                        vlabels = colnames(data), vlcex = 0.7,
                                        caxislabels = NULL, title = NULL, ...){
  radarchart(
    data, axistype = 1,
    pcol = color, pfcol = scales::alpha(color, 0.5), plwd = 2, plty = 1,
    cglcol = "grey", cglty = 1, cglwd = 0.8,
    axislabcol = "grey",
    vlcex = vlcex, vlabels = vlabels,
    caxislabels = caxislabels, title = title, ...
  )
}

colors <- c("#00AFBB", "#E0115F", "#800000", "orange")
titles <- c("UnderWeight", "NormalWeight", "OverWeight", "Obese")

# 设置2x2布局,避免图形覆盖
par(mfrow = c(2,2))

for(i in 1:4){
  create_beautiful_radarchart(
    data = df_fmsb[c(1,2, i+2),],  # 仅传入max、min和当前类别行
    caxislabels = c(5000,10000,15000,20000),
    color = colors[i], 
    title = titles[i],
    seg=3
  )
}

效果说明

修正后,每个雷达图会单独显示对应体重类别的数据,且坐标轴范围基于所有数据的max/min计算,图形会符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:35:15