R 中有没有办法叠加 3 个密度图,时间为 x 轴,计数为 y 轴?

Is there a way in R to overlay 3 density plots, with time as the x axis, and count as the y axis?

所以这让我很生气,如果有人能提供帮助,我会很高兴!

我有一个包含 3 列的日期集。每列都填有日期。每个日期代表社交媒体平台上的一个 post。例如,如果 2 post 人在 2012 年 10 月 10 日被 post 发布到 Twitter,则该日期将在 Twitter 列中记录两次。

我想在密度图中绘制每列随时间的分布。

我想要以月为单位的时间作为我的 x 轴。

我想要相对频率作为我的 y 轴....就像那个月在 Twitter 上有多少 post 的计数。所以对于 2012-10-10 的推特,它将是 2.

我希望所有分布都在同一个地块上,这样我就可以比较它们。

到目前为止,我已经尝试了无数种方法,但我似乎无法在同一张图表上获得以上所有方法,这让我抓狂!

我这里有密度图:

使用以下代码:

social_media_dates %>%
               ggplot( aes(x =`Facebook_dates`)) +
               geom_density(fill="#69b3a2", color="#e9ecef", alpha=0.8)+
               theme_bw()+
               scale_x_date(labels = date_format("%Y-%m"), breaks = date_breaks("3 months"), limits = c(as.Date("2016-12-01"), as.Date("2020-05-20"))) +
               labs(title = "Facebook posts over time")+
               xlab("month")+
               ylab("density")

但是:我不知道该怎么做] a) 将 y 轴更改为 posts 的计数 b) 将同一个图上的 3 个图与同一个轴合并

我最喜欢看起来像 ggridges 图的东西:

或者同一张图上的所有 3 条曲线。

我正在使用 ggplot 和 Rstudio 作为参考。

我已经尝试了很多东西,但它们总是失败!我正在考虑在图表中包含所有可能日期的 "date" 列,并将其作为我的 x 轴。然后在计数列中计算每天 posts 的计数。

例如。

date | facebook_count | twitter_count | instagram_count

2018-02-01 | 3 | 4 | 10

2018-02-02 | 4 | 8 | 2

2018-02-03 | NA | 4 | 6

我制作了一个看起来像这样的数据框,但我尝试过的所有图都坏了。

如果有人知道如何做到这一点,我将不胜感激!

您缺少的步骤是您需要将数据框更改为长格式

假设您的数据框如下所示

library(tidyverse)
library(scales)

df <- data.frame(fb= lubridate::ymd(c("2020-01-01","2020-01-02","2020-01-03", "2020-01-03")),
                      twi = lubridate::ymd(c("2020-01-05","2020-01-05","2020-01-6", "2020-01-09")),
                      insta = lubridate::ymd(c("2020-01-01","2020-01-02","2020-01-05", "2020-01-05"))
                      )

现在将数据框更改为长格式:

df_long <- df %>% pivot_longer(everything())

这可以绘制

df %>% ggplot( aes(x =value, color=name, fill= name)) +
  geom_density( alpha=0.8)+
  theme_bw()+
  scale_x_date(labels = date_format("%Y-%m"), 
               breaks = date_breaks("3 months")) +
  labs(title = "Posts over time")+
  xlab("month")+
  ylab("density")