0

I am drawing a cumulative freq polygon graph with R, I would like to separate the categories (three) to better see the trend difference. Unfortunately when I do that, they look on a different Y scale:

ggplot(aes(x = years, color = sex))+
  geom_freqpoly(aes(y = cumsum(..count..)), binwidth = 2)

This is the code and the output

enter image description here

I would like all categories starting from count 0. Thank you for your help

Question solved, example with sample dataset:

df <- data.frame(
  year = c(1980, 1980, 1980, 1982, 1982, 1982, 1982, 1982,
          1990, 1990, 1990, 1990, 1990, 1990, 1990,
          1990, 1991, 1991, 1991, 1991, 1991, 1993, 1993),
  sex = c("Un", "Ma", "Fe", "Ma", "Fe", "Un", "Un", "Fe", "Ma"
          , "Ma", "Ma", "Ma", "Fe", "Fe", "Fe", "Ma", "Ma", "Fe", "Ma", 
          "Ma", "Fe", "Fe", "Ma")
)

library(ggplot2)
df |> 
  ggplot(aes(x = year, color = sex)) +
  geom_freqpoly(aes(y=cumsum(..count..)))

#cumsum does not take into account the grouping by color = sex
#use ave or tapply instead

df |> 
  ggplot(aes(x = year, color = sex)) +
  geom_freqpoly((aes(y = after_stat(ave(count, color, FUN = cumsum)))))
MrFlick
  • 195,160
  • 17
  • 277
  • 295
Marti
  • 1
  • 2
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Aug 28 '23 at 15:31
  • I tried but it doesn't work: geom_freqpoly(position = "identity", aes(y = cumsum(..count..))) – Marti Aug 28 '23 at 15:32
  • 3
    One issue is that `cumsum(..count..)` will not account for the grouping by `color=sex`. Instead try with `geom_freqpoly(aes(y = after_stat(ave(count, color, FUN = cumsum))), binwidth = 2)`. – stefan Aug 28 '23 at 15:37
  • 1
    @stefan you're right - another one for `ave` or `tapply` – Allan Cameron Aug 28 '23 at 15:38
  • 1
    @stefan that works! Thank you so much, you made my day!! – Marti Aug 28 '23 at 15:51
  • 1
    @Marti, _another_ option (in lieu of waiting until next time) is to add sample data here and self-answer using stefan's recommendation. If not, this question will either be culled (eventually) or voted-to-delete after being closed as not-reproducible. (Or you can just delete it, over to you.) – r2evans Aug 28 '23 at 16:23
  • @r2evans thanks I'm an absolute beginner – Marti Aug 28 '23 at 16:57

0 Answers0