使用ggplot2
會更容易。但你也可以嘗試做這樣說:
#Random numbers
set.seed(11235)
h1 <- rnorm(1000, 6)
h2 <- rnorm(1000, 4)
# Histogram Colored (blue and red), alpha value corresponds to freq.
hist(h1,
col=rgb(1, 0, 0, hist(h1, plot = F)$density),
xlim = c(0, 10),
ylim = c(0, 200),
xlab='Variable',
main='Overlapping Histogram'
)
hist(h2, col = rgb(0, 0, 1, hist(h2, plot = F)$density), add = T)
box()
# Histogram Colored (blue and red), alpha value corresponds
# to variable value.
mynorm <- function(x){
return((x-min(x))/(max(x)-min(x)))
}
hist(h1,
col=rgb(1, 0, 0, mynorm(hist(h1, plot = F)$mids)),
xlim = c(0, 10),
ylim = c(0, 200),
xlab='Variable',
main='Overlapping Histogram'
)
hist(h2, col = rgb(0, 0, 1, mynorm(hist(h2, plot = F)$mids)), add = T)
box()
所以您只需使用頻率|變量值作爲你的RGB顏色的阿爾法值規範。
您可能想看看最近發佈的ggplot2及其顏色縮放功能[R博客文章](https://www.r-bloggers.com/overlapping-histogram-in-r/) –