[英]Shading in bars in barchart in R
我正在使用此代碼在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()
這段代碼產生了這個圖:
我一直試圖找出的是如何使條形的暗度與數據中的值相對應。 換句話說,對於變量“ h1”,我如何使較大的值具有深色欄?
謝謝!!
使用ggplot2
會容易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值即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.