标准化ggplot直方图,使R中的第一个高度为1(显示增长)

我想知道是否有办法将多个组的直方图的高度标准化,以便它们的第一高度全部= 1.例如:

results <- rep(c(1,1,2,2,2,3,1,1,1,3,4,4,2,5,7),3)
category <- rep(c("a","b","c"),15)
data <- data.frame(results,category)
p <- ggplot(data, aes(x=results, fill = category, y = ..count..))
p + geom_histogram(position = "dodge")

给出了3组的常规直方图.

results <- rep(c(1,1,2,2,2,3,1,1,1,3,4,4,2,5,7),3)
category <- rep(c("a","b","c"),15)
data <- data.frame(results,category)
p <- ggplot(data, aes(x=results, fill = category, y = ..ncount..))
p + geom_histogram(position = "dodge")

给出一个直方图,其中每个组被归一化为最大高度为1.
我想得到一个直方图,其中每个组被标准化为第一个高度为1(所以我可以显示增长)但我不明白是否有适当的替代..ncount或..count ..或者如果有人可以帮助我理解..count的结构..我可以从那里弄明白.
谢谢!

最佳答案 我敢打赌,在ggplot中做一切都有很好的方法.但是,我倾向于在将其插入ggplot之前准备好所需的数据集.如果我理解正确,您可以尝试这样的事情:

# convert 'results' to factor and set levels to get an equi-spaced 'results' x-axis
df$results <- factor(df$results, levels = 1:7)

# for each category, count frequency of 'results' 
df <- as.data.frame(with(df, table(results, category)))

# normalize: for each category, divide all 'Freq' (heights) with the first 'Freq'
df$freq2 <- with(df, ave(Freq, category, FUN = function(x) x/x[1]))

ggplot(data = df, aes(x = results, y = freq2, fill = category)) +
  geom_bar(stat = "identity", position = "dodge")
点赞