如何在R直方图中为特定数据条着色

时间:2014-12-04 13:48:36

标签: r

如果我有直方图:

> hist(faithful$waiting,seq(min(faithful$waiting),max(faithful$waiting)))

和#34;特殊"频率:

> c(51, 52, 57, 59, 64)

是否可以将与这些特殊频率相对应的条纹颜色与其他组织的颜色区别开来?

2 个答案:

答案 0 :(得分:4)

您只需创建颜色矢量并使用col选项。

data(faithful)

# make sure frequencies in order and unique for the histogram call
special <- ifelse(sort(unique(faithful$waiting)) %in% c(51, 52, 57, 59, 64), "red", "white")

# same call with the 'col' option
hist(faithful$waiting,seq(min(faithful$waiting),max(faithful$waiting)), col=special)

enter image description here

答案 1 :(得分:2)

ggplot2的乐趣...

faithful$special <- faithful$waiting %in% c(51, 52, 57, 59, 64)

library(ggplot2)

ggplot(data = faithful, aes(x = waiting, fill = special)) +
  geom_histogram(binwidth = 1, colour = 'white')

enter image description here