R 在同一图形中创建4个百分比条形图,并将每个图形中的计数重置为0

R 在同一图形中创建4个百分比条形图,并将每个图形中的计数重置为0,r,plot,ggplot2,facet-wrap,R,Plot,Ggplot2,Facet Wrap,我有一个数据帧(dat2),带有: 我已经从stackoverflow中收集了一些代码,以便创建一个显示百分比的4方面绘图条 ggplot(dat2,aes(x=Groups)) + stat_bin(aes(n=nrow(dat2), y=..count../n)) + scale_y_continuous(formatter = "percent") + facet_wrap(~ label) 问题是我想为每个子批次重置计数器,这样每个标签组数据将被计算为除以特定标签中的行

我有一个数据帧(dat2),带有:

我已经从stackoverflow中收集了一些代码,以便创建一个显示百分比的4方面绘图条

ggplot(dat2,aes(x=Groups)) + 
  stat_bin(aes(n=nrow(dat2), y=..count../n)) +
  scale_y_continuous(formatter = "percent") + 
  facet_wrap(~ label)

问题是我想为每个子批次重置计数器,这样每个标签组数据将被计算为除以特定标签中的行总数,而不是除以总数。

计算每个标签的观察数,并将其添加到数据集

nLabel <- 4
nGroups <- 3
nObs <- 10000
dataset <- data.frame(label = factor(sample(nLabel, nObs, prob = runif(nLabel), replace = TRUE)))
library(plyr)
dataset <- ddply(dataset, .(label), function(x){
  data.frame(Groups = sample(nGroups, nrow(x), prob = runif(nGroups), replace = TRUE))
})
dataset$nLabel <- ave(dataset$Groups, by = dataset$label, FUN = length)
dataset$Groups <- factor(dataset$Groups)
library(ggplot2)
library(scales)
ggplot(dataset, aes(x = Groups)) + geom_histogram(aes(n = nLabel, y = ..count.. / n)) + facet_wrap(~label, scales = "free") + scale_y_continuous(label = percent)

nLabel请使用例如
dput
给我们dat2,使您的示例可复制。请注意,完整的数据集可能太大,请只包含一个小的子集来再现您的情况(~50行)。对我来说,关键是要看到n=nLabel是观察的数量。是我的错。
nLabel <- 4
nGroups <- 3
nObs <- 10000
dataset <- data.frame(label = factor(sample(nLabel, nObs, prob = runif(nLabel), replace = TRUE)))
library(plyr)
dataset <- ddply(dataset, .(label), function(x){
  data.frame(Groups = sample(nGroups, nrow(x), prob = runif(nGroups), replace = TRUE))
})
dataset$nLabel <- ave(dataset$Groups, by = dataset$label, FUN = length)
dataset$Groups <- factor(dataset$Groups)
library(ggplot2)
library(scales)
ggplot(dataset, aes(x = Groups)) + geom_histogram(aes(n = nLabel, y = ..count.. / n)) + facet_wrap(~label, scales = "free") + scale_y_continuous(label = percent)