【问题标题】:Change colour of specific histogram bins in R更改 R 中特定直方图箱的颜色
【发布时间】:2016-05-07 08:00:53
【问题描述】:

我使用绘图功能创建了以下直方图:

hist(mst$Total[which(mst$Total<100)], axes = TRUE, ylab = "", xlab = "", main = "", col = "chartreuse4", breaks = tb, freq=TRUE, right = FALSE)

中断已指定如下:

tb = c(0,1,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100)

我希望能够用不同的颜色填充特定的直方图箱。

颜色一: [0,1)

颜色二: [1,5)

颜色三: [5,10) [10,15) 和 [15,20)

颜色四: 从 [20,25] 开始的所有 bin

如何使用 r 基础包图形来做到这一点?

非常感谢

更新为接受的答案:

使用接受的答案,我能够创建以下图:

range <- c(0, 1, 5, 20, 100)
col <- findInterval(tb, range, all.inside = TRUE)
col[which(col==1)] <- "firebrick1"

col[which(col==2)] <- "gold"
col[which(col==3)] <- "darkolivegreen1"
col[which(col==4)] <- "forestgreen"
hist(mst$Total[which(mst$Total<100)], axes = TRUE, ylab = "", xlab = "", main = "", col = col, breaks = tb, freq=TRUE, right = FALSE)

【问题讨论】:

  • 类似hist(rnorm(1000), col = c(1, 2, 3, 3, rep(4, length(tb)-4)))?

标签: r histogram


【解决方案1】:

首先我们定义你的颜色区间

tb <- c(0,1,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100)
range <- c(0, 1, 5, 20, 100)

然后安排你的休息时间

col <- findInterval(tb, range, all.inside = TRUE)
col
[1] 1 2 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4

然后您可以使用 col 为每个 bin 着色

hist(mst$Total[which(mst$Total<100)], axes = TRUE, ylab = "", xlab = "", main = "", col = col, breaks = tb, freq=TRUE, right = FALSE)

很遗憾,由于您没有提供数据,因此我无法对其进行测试,但这应该可以。

【讨论】:

  • 效果很好!有没有办法指定颜色而不是获取默认值?我可以用实际的颜色名称替换 col 向量中的数字吗?
  • 当然,只需将1 2 3 ... 替换为您的实际颜色名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
  • 2018-12-30
  • 2017-03-25
相关资源
最近更新 更多