没有 y 变量的堆积面积图 ggplot2

问题描述 投票:0回答:1

我需要使用以下数据集创建堆积面积图(示例):

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
元素的计数或比例?

ggplot2 geom-area
1个回答
0
投票

您可以

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

© www.soinside.com 2019 - 2024. All rights reserved.