![](/img/trans.png)
[英]R baseplot :plotting 2 density plots in 1 plot cand hanging scales for x-Axis and y-Axis
[英]Is there a way in R to overlay 3 density plots, with time as the x axis, and count as the y axis?
所以這一直讓我發瘋,如果有人能幫忙,我會很高興的!
我有一個包含 3 列的日期集。 每列都填滿了日期。 每個日期代表社交媒體平台上的帖子。 例如,如果 2012 年 10 月 10 日在 twitter 發布了 2 個帖子,則該日期將在 twitter 列中記錄兩次。
我想以密度 plot 繪制這些列隨時間的分布。
我想要以幾個月為單位的時間作為我的 x 軸。
我想要相對頻率作為我的 y 軸....就像當月 twitter 上有多少帖子一樣。 因此,對於 2012 年 10 月 10 日的 twitter,它將是 2。
我希望所有分布都在同一個 plot 上,以便我可以比較它們。
到目前為止,我已經嘗試了很多事情,但我似乎無法將以上所有內容都放在同一張圖上,這讓我發瘋了!
我在這里制作了密度圖:
使用以下代碼:
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 軸更改為帖子數 b) 將同一圖表上的 3 個圖與同一軸合並
理想情況下,我喜歡看起來像 ggridges 情節的東西:
或者只是同一圖表上的所有 3 條曲線。
我正在使用 ggplot 和 Rstudio 作為參考。
我已經嘗試了很多東西,但它們只是一直在失敗,我正在考慮有一個“日期”列,其中包含所有可能的日期。 並將其作為我的 x 軸。 然后在計數列中計算每天的帖子數。
例如。
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
我已經制作了一個看起來像這樣的 dataframe,但是我嘗試過的所有情節都已損壞。
如果有人知道如何做到這一點,我將不勝感激!
您缺少的步驟是您需要將 dataframe 更改為長格式
假設您的數據框如下所示
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.