2016-11-17 73 views
0

我使用這個代碼,以使重疊的直方圖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() 

這段代碼產生這樣的情節:

overlapping histogram

我有什麼一直試圖弄清楚的是,我可以如何使條形的黑暗對應於我的數據中的值。換句話說,對於變量「h1」,我怎麼能讓更大的值有更深的彩條?

謝謝!

+0

您可能想看看最近發佈的ggplot2及其顏色縮放功能[R博客文章](https://www.r-bloggers.com/overlapping-histogram-in-r/) –

回答

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

alpha~frequency histogram

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

alpha~variable value

所以您只需使用頻率|變量值作爲你的RGB顏色的阿爾法值規範。

+0

對不起,第二部分是錯的,我做了版。 – utubun

+0

感謝您的回覆。這工作很好!一個後續問題:我怎樣才能讓一個變量(左邊的藍色)和另一個變量(右邊的那個)上的值更高,陰影變得更暗一些? – user2917781

+0

您只需將h1中的alpha值向量逆轉: 'rev(mynorm(hist(h1,plot = F)$ mids))' 您將得到類似[this](https:// www .dropbox.com/s/l1jyrow9q1b5gur/baseHist.jpeg?dl = 0) 但是用這種方式做這樣的事情是有點運動的。我還沒有嘗試過,但我認爲使用'ggplot2'會更容易。 – utubun