I need to create a stacked area chart with the following dataset (example):
ds <- data.frame(
Time = c(rep(1, 4), rep(2, 4)),
Type = c("a", "c", "f", "f", "e", "q", "a", "c")
)
I know the formula should be:
ggplot(ds, aes(x=time, y=???, fill=Type)) +
geom_area()
My question is what do I put in the y
value to have the count or the proportion of Type
elements for each given Time
?
You can count
the occurrences of different Types
at each Time
point, then map that variable to the y-axis.
set.seed(123)
ds <- data.frame(
Time = rep(1:10, each = 50),
Type = sample(LETTERS[1:6], 500, replace = TRUE, prob = c(0.1,0.15,0.2,
0.1,0.25,0.2))
)
library(ggplot2)
library(dplyr)
ds |>
count(Time, Type) |>
ggplot(aes(x = Time, y = n, fill = Type)) +
geom_area()
Created on 2024-04-05 with reprex v2.0.2