问题描述:

I'm using this code to make an overlapping histogram in 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()

This code produces this plot:

overlapping histogram

What I've been trying to figure out is how I can make the darkness of the bars correspond to values in my data. In other words, for the variable "h1" how can I make larger values have darker colored bars?

Thanks!!

网友答案:

It would much more easier to do using ggplot2. But you can also try to do it this way:

#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()

So you simply use frequencies|variable-values as a alpha-values in your rgb-color specification.

相关阅读:
Top