How can I create a frequency plot/histogram in R using ggplot2 while normalizing to the total of a factor?
One option would be to use e.g. ave() to compute the count per group or Timepoint:
library(ggplot2)

ggplot(data = DS, aes(x = X)) +
  geom_freqpoly(
    aes(
      colour = TimePoint,
      y = after_stat(count / ave(count, group, FUN = sum))
    )
  )
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.



My problem is the following: I can make a figure in which the data is weighed relative to the entire population, but not relative to their own subpopulation. To illustrate with an example:
Suppose I have a dataset DS, with two columns: X and type.
X is a continues value ranging from -5 to 5, and type is either A, B or C.
How would I create a frequency plot of X in which each tuple is weighed by the total of its type, not the total of all tuples in the dataset?
This is my closest attempt, yet it weighs to the total population:
figure1 <- ggplot(data = DS, aes(x = X))+ geom_freqpoly(aes(colour = type, y= after_stat(count / sum(count)))) + ...
Its not surprising that this normalizes to the entire dataset, but I wouldnt know how to get it such that it only normalizes to a subset.
Using dput(), I generate the following example dataframe:
DS <- structure(list(X = c(0, -0.01, 0.042944432215413, 0.0431301011419889, 0.042944432215413, 0.0424042102083902, 0.2100000012 , 0.13513333335333), TimePoint = c("early", "early", "late", "mid", "mid", "early", "late", "early")), row.names = c(NA,8L), class = "data.frame")

In which 'X' is the continous value and 'TimePoint' is the factor which can be either 'early', 'mid' or late.
