【问题标题】:How do I overlay different years from a POSIXct dataset in a histogram with ggplot?如何使用 ggplot 在直方图中覆盖来自 POSIXct 数据集的不同年份?
【发布时间】:2022-01-16 03:42:30
【问题描述】:

我有一个包含 POSIXct 格式的日期和时间的大型数据集。这基本上跨越了两个学年。

#Earliest / last log 
#2018-09-02 14:46:56
#2020-10-12 23:30:13 

我设法在 2019 年 9 月 1 日添加了一个学年 True / False 列来拆分两年:

MViews$AcademicYear1819 <- MViews$earliestlog <= as.Date("2019-09-01 00:00:00")

当我绘制这个 ggplot 时,将所有内容按时间顺序放在 x 轴上,但我想将两个学年相互叠加。

MViews %>% 
  ggplot(aes(x = earliestlog, fill = "red")) + geom_density(alpha = 0.5)

所以基本上 2018 年 9 月和 2019 年 9 月都从 x = 0 开始。

我尝试了很多东西,但不幸的是没有任何效果。我什至尝试将一年前的学年返回为 true 的所有值增加一年,但这无论如何都不起作用。

MViews$EL <- MViews$EL[MViews$AcademicYear1819] %m+% years(1) & MViews$EL[!MViews$AcademicYear1819]

UseMethod("reclass_date", orig) 中的错误: 没有适用于“重新分类日期”的方法应用于“NULL”类的对象 另外:警告信息: 1:未知或未初始化的列:EL

【问题讨论】:

  • 制作一个“假日期”列,其中所有的 9-12 月都是同一年(比如 2018 年),所有 1-8 月的日期都是明年(2019 年),然后把假的x 轴上的日期列。
  • 如果您需要更多帮助,请添加足够的数据来重现问题,最好以复制/粘贴的方式,dput(MViews[1:10, ]) 将为我们提供前 10 行的复制/粘贴版本 -选择一个合适的子集。

标签: r ggplot2


【解决方案1】:

无法确定您是否想要与构面相同的图形叠加层或顶部的图形。如果只有一张图,请删除下面的刻面位。我还使用了 3 年的跨度来进行演示。

library(lubridate)


#Generate dataset
set.seed(123)
df <- sample(seq.POSIXt(from =as.POSIXlt('2018-09-02 14:46:56'), to = as.POSIXlt('2020-10-12 23:30:13'), by = "hour"), 1000, replace = TRUE)
df

#Create semester objects to exclude summer months-- step may not be necessary
fallstr = c("Sep", "Oct", "Nov","Dec")
springstr = c("Jan", "Feb","Mar","Apr")


df %>% 
    as_tibble() %>% 
    mutate(year = year(value),
           month = month(value, label = TRUE)) %>% 
#Removing summer months
    filter(month %in% c(fallstr,springstr)) %>% 
#Reordering factor levels used for graphing x-axis later
    mutate(month = factor(month, levels = c(fallstr,springstr))) %>%
#Reclassifying cases into academic years 
    mutate(academic_year = case_when(
        month %in% fallstr & year == 2018 ~ "Year 1",
        month %in% springstr & year == 2019 ~ "Year 1",
        month %in% fallstr & year == 2019 ~ "Year 2", 
        month %in% springstr & year == 2020 ~ "Year 2",
        #May not need year 3 but just included for demo purpose
        month %in% fallstr & year == 2020 ~ "Year 3")) %>% 
#Can use if you want visualize the year, just swap-comment with other ggplot
    #ggplot(aes(x = month, fill = as.factor(year))) +
    ggplot(aes(x = month, fill = academic_year)) +
    geom_histogram(position = "identity", bins =4, alpha = .4, stat = "count") +
    facet_wrap(.~academic_year, ncol = 1)

如果您有其他想法,请告诉我

【讨论】:

    猜你喜欢
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    相关资源
    最近更新 更多