我使用此代码在R中制作重叠的直方图。
#Random numbers
h2<-rnorm(1000,4)
h1<-rnorm(1000,6)
# Histogram Colored (blue and red)
hist(h1, col=rgb(1,0,0,0.5),xlim=c(0,10), ylim=c(0,200), main="Overlapping Histogram”, xlab="Variable”)
hist(h2, col=rgb(0,0,1,0.5), add=T)
box()
此代码生成此图:
我一直想弄清楚的是如何让条形图的黑暗与我数据中的值相对应。换句话说,对于变量&#34; h1&#34;如何使较大的值具有较深的彩色条?
谢谢!
答案 0 :(得分:1)
使用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颜色规范中的alpha值。