2014-02-18 100 views
1

使用示例數據:磨製使用ggplot R中

#天1

carrots <- data.frame(length = rnorm(100000, 6, 2)) 
cukes <- data.frame(length = rnorm(50000, 7, 2.5)) 

#Now,你的兩個dataframes合二爲一。首先在每個中創建一個新列。

carrots$veg <- 'carrot' 

cukes$veg <- 'cuke' 

#,然後組合成新的數據幀vegLengths

vegLengths <- rbind(carrots, cukes) 

#now讓你的可愛情節

ggplot(vegLengths, aes(length, fill = veg)) + geom_histogram(alpha = 0.5), position = 'identity') 

#每日2

carrots <- data.frame(length = rnorm(600000, 6, 2)) 

cukes <- data.frame(length = rnorm(70000, 7, 2.5)) 

#Now, combine your two dataframes into one. First make a new column in each. 

carrots$veg <- 'carrot' 

cukes$veg <- 'cuke' 

#,然後組合成新的數據幀vegLengths

vegLengths <- rbind(carrots, cukes) 

#now讓你的可愛情節

ggplot(vegLengths, aes(length, fill = veg)) + geom_histogram(alpha = 0.5), position = 'identity') 

我有一個類似的數據集,並決定用這個更容易理解。我有兩個這樣的情節。如何使用刻面選項並將day1和day2一起表示在一個繪圖中以便比較它們?

回答

1

首先,你必須將所有的數據合併到一個數據幀:

carrots1 <- data.frame(length = rnorm(100000, 6, 2)) 
cukes1 <- data.frame(length = rnorm(50000, 7, 2.5)) 
carrots1$veg <- 'carrot' 
cukes1$veg <- 'cuke' 
vegLengths1 <- rbind(carrots1, cukes1) 
vegLengths1$day <- '1' 

carrots2 <- data.frame(length = rnorm(600000, 6, 2)) 
cukes2 <- data.frame(length = rnorm(70000, 7, 2.5)) 
carrots2$veg <- 'carrot' 
cukes2$veg <- 'cuke' 
vegLengths2 <- rbind(carrots2, cukes2) 
vegLengths2$day <- '2' 

vegLengths <- rbind(vegLengths1, vegLengths2) 

你可以用一個情節後:

require(ggplot2) 

ggplot(vegLengths, aes(x=length, fill = veg)) + 
    geom_histogram(binwidth=0.5, alpha = 0.5, position = 'identity') + 
    facet_wrap(~ day) 

結果: enter image description here