2015-04-28 131 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()