2015-04-28 79 views
5

我想從下面的數據的R - 直方圖

a 11 
a 14 
a 23 
b 12 
b 21 
c 17 
c 14 
c 29 
c 22 
c 25 

產生直方圖內直方圖這是我的目標情節

enter image description here 貌似我可以做這樣的事情與ggplot但我沒有ggplot在我的系統中。沒有ggplot可以生成它嗎?

+2

你似乎想要計算10-20和20-30範圍內的出現次數?爲什麼順便說一句不是install.packages(「ggplot2」)? –

+0

爲什麼你不能下載ggplot2? – miles2know

+1

我正在使用我沒有太多控制權的服務器上工作。需要很長時間/努力/升級才能在這些遠程服務器上完成某些任務 – SAN

回答

4

更新

這裏的一個更好的版本,其可以更容易地調整到任何數目的代碼的範圍由以分離:

dat <- data.frame(c1 = c("a", "a", "a", "b", "b", rep("c", 5)), c2=c(11, 14, 23, 12, 21, 17, 14, 29, 22, 25)) 

groups <- levels(dat$c1) 
nranges <- 2 
limits <- c(10, 20, 30) #Must have length equal to nranges + 1 
intervals <- sapply(1:nranges, function(i) paste0(limits[i], "-", limits[i+1])) 

frequencies <- sapply(1:nranges, function(i) sapply(groups, function(j) sum(dat[dat$c2>limits[i] & dat$c2<limits[i+1],1]==j))) 
# Or using table(). One of them might be faster than the other for large data 
#frequencies <- sapply(1:nranges, function(i) rowSums(table(dat[dat$c2>limits[i] & dat$c2<limits[i+1],]))) 

barplot(frequencies, beside = TRUE, col=1:length(groups), names.arg=intervals) 

的結果是相同的,如下面不同的顏色和各組相應的標籤:

enter image description here

原始

這可能不是適合您真實的數據,但它的工作原理爲您的樣品,並會給你一個開始:

dat <- data.frame(c1 = c("a", "a", "a", "b", "b", rep("c", 5)), c2=c(11, 14, 23, 12, 21, 17, 14, 29, 22, 25)) 

groups <- levels(dat$c1) 
dat1 <- sapply(groups, function(i) sum(dat[dat$c2>10 & dat$c2<20,1]==i)) 
dat2 <- sapply(groups, function(i) sum(dat[dat$c2>20 & dat$c2<30,1]==i)) 

barplot(matrix(c(dat1, dat2), ncol=2), beside = TRUE, col=c("Red", "Green", "Blue")) 

產生:

enter image description here

的想法是計算頻率,然後使用帶有堆疊數據的barplot並排繪圖,而不是嘗試使用hist()