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

理解R语言cut函数 解决直方图随机10%样本标红颜色不显示问题

R 直方图10%数据标红问题修复

问题说明

目标是绘制正态分布随机数的直方图,随机选取10%的样本标记为红色,原有代码运行后颜色未按预期生效。

初始代码

a = rnorm(100000,60000,1000)
b = a

c = data.frame(a,b)
color <- c("black", "red")     
color_1 <- sample(color, nrow(c), replace=TRUE, prob=c(0.9, 0.1))
c$color_1 = as.factor(color_1)


hist(c$a, col = c$color_1, 100000, main = "title")

legend("topleft", legend=c("group a", "group b"),
       col=c("red", "black"), lty = 1, cex=0.8)
title(
      sub = "some title")

异常现象

异常直方图效果

已尝试的调整方案

  • 直接修改hist函数的col参数传入color_1变量
hist(c$a, col = color_1, 100000, main = "title")
  • 取消color_1的factor类型定义
a = rnorm(100000,60000,1000)
b = a

c = data.frame(a,b)
color <- c("black", "red")     
color_1 <- sample(color, nrow(c), replace=TRUE, prob=c(0.9, 0.1))
c$color_1 = color_1


hist(c$a, col = c$color_1, 100000, main = "title")

legend("topleft", legend=c("group a", "group b"),
       col=c("red", "black"), lty = 1, cex=0.8)
title(
      sub = "some title")
  • 使用cut函数处理直方图断点
h = hist(c$a, col = c$color_1, breaks = 100000, main = "title")

legend("topleft", legend=c("group a", "group b"),
       col=c("red", "black"), lty = 1, cex=0.8)
title(
      sub = "some title")



cuts <- cut(h$breaks, c(-Inf,Inf))
plot(h, col=cuts)

问题根因

hist函数的col参数用于给直方图的每个柱子指定填充色,而非给每个原始数据点指定颜色。你传入了和样本量一致的10万个颜色值,但直方图的柱子数量远小于10万,R只会循环取前几位颜色值,因此无法实现给10%样本标红的需求。

修复代码

# 生成测试数据
a = rnorm(100000,60000,1000)
# 随机标记10%的样本为红色组
flag <- sample(c(FALSE, TRUE), length(a), replace = TRUE, prob = c(0.9, 0.1))
group_black <- a[!flag]
group_red <- a[flag]

# 基于全量数据统一计算断点,保证两组直方图柱子对齐
all_breaks <- hist(a, breaks = 100, plot = FALSE)$breaks
# 绘制占比90%的黑色组直方图
hist(group_black, breaks = all_breaks, col = "black", main = "title", xlab = "数值")
# 叠加绘制占比10%的红色组直方图,add=TRUE表示在当前画布叠加
hist(group_red, breaks = all_breaks, col = "red", add = TRUE)

# 添加图例和副标题
legend("topleft", legend = c("90%普通组", "10%标记组"),
       fill = c("black", "red"), cex = 0.8)
title(sub = "some title")

核心修改点

  • 提前将样本拆分为普通组和标记组,分别统计直方图
  • 统一设置两组的直方图断点,避免柱子错位
  • 用add=TRUE参数叠加绘制标记组的直方图
  • 图例使用fill参数对应直方图填充色,展示效果一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:06:05