R - 直方图中的直方图

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

最佳答案

更新

这是代码的更好版本,可以更轻松地将其调整为任何数字范围以分隔:

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() .

关于R - 直方图中的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29920876/

相关文章:

r - 我应该 (git) 忽略我的 knitr 缓存吗?

r - ggplot 分组 geom_bar - 将因子类别的标签添加到 x 轴标签

r - 使用 R 计算边际税率

r - geom_text_repel 中的条件尺寸和面孔

r - 如何在 ggtern 中显示数据的真实值 (%)?

r - 如何在Dockerfile中的多个CMD语句之间保留R工作区?

r - ggplot2 堆叠条形图,其中每个值都是一个组/颜色

返回 R 中向量中条件选择对的最大值

python - 抓取搜索/身份验证生成的页面

r - 使用DT包隐藏响应数据表中的某些列