我需要使用以下数据集创建堆积面积图(示例):
ds <- data.frame(
Time = c(rep(1, 4), rep(2, 4)),
Type = c("a", "c", "f", "f", "e", "q", "a", "c")
)
我知道公式应该是:
ggplot(ds, aes(x=time, y=???, fill=Type)) +
geom_area()
我的问题是我应该在
y
值中放入什么以获得每个给定 Type
的 Time
元素的计数或比例?
您可以
count
在每个 Types
点处出现不同的 Time
,然后将该变量映射到 y 轴。
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()
创建于 2024-04-05,使用 reprex v2.0.2