2011-05-17 39 views
7

假設我有這個數據框有2個級別。 LC和HC。 現在我想要得到像下面這樣的2個情節。在沒有箱子的情況下在彼此頂部的多個直方圖

data <- data.frame(
    welltype=c("LC","LC","LC","LC","LC","HC","HC","HC","HC","HC"), 
    value=c(1,2,1,2,1,5,4,5,4,5)) 

代碼即可獲得以下情節=

x <- rnorm(1000) 
y <- hist(x) 
plot(y$breaks, 
    c(y$counts,0), 
    type="s",col="blue") 

(與感謝里斯Meys)

所以,我怎麼甚至開始在這。由於我習慣了java,我正在考慮for循環,但我被告知不要這樣做。

enter image description here

回答

4

您可以使用相同的代碼除外點的情節,而不是添加額外的線的情節。

製作了一些數據

set.seed(5) 
d <- data.frame(x=c(rnorm(1000)+3, rnorm(1000)), 
       g=rep(1:2, each=1000)) 

而且在一個相當簡單的方法做:

x1 <- d$x[d$g==1] 
x2 <- d$x[d$g==2] 
y1 <- hist(x1, plot=FALSE) 
y2 <- hist(x2, plot=FALSE) 
plot(y1$breaks, c(y1$counts,0), type="s",col="blue", 
    xlim=range(c(y1$breaks, y2$breaks)), ylim=range(c(0,y1$counts, y2$counts))) 
points(y2$breaks, c(y2$counts,0), type="s", col="red") 

或者更R-ISH方式:

col <- c("blue", "red") 
ds <- split(d$x, d$g) 
hs <- lapply(ds, hist, plot=FALSE) 
plot(0,0,type="n", 
    ylim=range(c(0,unlist(lapply(hs, function(x) x$counts)))), 
    xlim=range(unlist(lapply(hs, function(x) x$breaks)))) 
for(i in seq_along(hs)) { 
    points(hs[[i]]$breaks, c(hs[[i]]$counts,0), type="s", col=col[i]) 
} 

編輯:靈感通過Joris的回答,我會注意到格子也可以很容易地做重疊的密度圖。

​​
13

接下來由阿龍提供的方法,有一個ggplot解決方案,以及(見下文), 但我強烈建議你使用的密度,因爲他們將給予更好的情節,是一個容易許多構建:

# make data 
wells <- c("LC","HC","BC") 
Data <- data.frame(
    welltype=rep(wells,each=100), 
    value=c(rnorm(100),rnorm(100,2),rnorm(100,3)) 
) 

ggplot(Data,aes(value,fill=welltype)) + geom_density(alpha=0.2) 

給出:enter image description here

對於你所要求的情節:

# make hists dataframe 
hists <- tapply(Data$value,Data$welltype, 
      function(i){ 
       tmp <- hist(i) 
       data.frame(br=tmp$breaks,co=c(tmp$counts,0)) 
      }) 
ll <- sapply(hists,nrow) 
hists <- do.call(rbind,hists) 
hists$fac <- rep(wells,ll) 

# make plot 
require(ggplot2) 
qplot(br,co,data=hists,geom="step",colour=fac) 

enter image description here

+0

哦,這些都很好。我必須學習ggplot。 – Aaron 2011-05-17 15:03:47

相關問題