R - 直方图内的直方图

时间:2015-04-28 13:26:22

标签: 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的情况下生成它?

1 个答案:

答案 0 :(得分: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

我们的想法是计算频率,然后使用带有堆叠数据的条形图并排绘制,而不是尝试使用hist()