我想使用ggplot2在一张图中绘制多个密度图:
我的df
如下:
structure(list(item_count = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L,
5L, 5L, 6L, 8L), created_at = structure(c(18319, 18321, 18319,
18321, 18319, 18321, 18319, 18321, 18319, 18321, 18319, 18321
), class = "Date"), frequency = c(2L, 2L, 3L, 6L, 586L, 419L,
268L, 238L, 5L, 2L, 1L, 1L)), row.names = c(NA, -12L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), groups = structure(list(item_count = c(1L,
2L, 3L, 4L, 5L, 6L, 8L), .rows = list(1:2, 3:4, 5:6, 7:8, 9:10,
11L, 12L)), row.names = c(NA, -7L), class = c("tbl_df", "tbl",
"data.frame"), .drop = TRUE))
aka:
# A tibble: 12 x 3
# Groups: item_count [7]
item_count created_at frequency
<int> <date> <int>
1 1 2020-02-27 2
2 1 2020-02-29 2
3 2 2020-02-27 3
4 2 2020-02-29 6
5 3 2020-02-27 586
6 3 2020-02-29 419
7 4 2020-02-27 268
8 4 2020-02-29 238
9 5 2020-02-27 5
10 5 2020-02-29 2
11 6 2020-02-27 1
12 8 2020-02-29 1
我尝试过:
library(tidyverse)
library(ggplot2)
df %>%
ggplot(aes(item_count, frequency), colors=created_at) + geom_density()
遇到此错误:
Error: geom_density requires the following missing aesthetics: y
我在做什么错?
答案 0 :(得分:1)
尝试
df %>%
ggplot(aes(item_count, frequency, col = created_at)) +
geom_density(stat = "identity")
答案 1 :(得分:0)
您已经知道商品的投放频率,因此只需排队:
ggplot(df,aes(x=item_count,y=frequency,col=factor(created_at))) + geom_line()
您可以像这样重建后一种以得到密度,但是我认为您的频率表很奇怪:
obs = data.frame(counts=rep(df$item_count,df$frequency),
created_at=rep(df$created_at,df$frequency))
ggplot(obs,aes(x=counts,col=factor(created_at))) + geom_density(bw=0.33)
可能需要找到合适的bw
observed_data