Search code examples
rvistime

how to add year details on x axis gg_vistime


I'm fairly new to R and I have a problem with how to add year details on the x-axis? (pic below), default settings only show 2002-2012 with 2-year intervals. meanwhile, I want to add 2003, 2005, 2007.. etc to show every year

timeline

my dataset in the form of dput():

structure(list(start_year = structure(c(978307200, 1009843200, 
1041379200, 1072915200, 1104537600, 1136073600, 1167609600, 1199145600, 
1230768000, 1262304000, 1293840000, 1325376000, 1356998400), class = c("POSIXct", 
"POSIXt"), tzone = "UTC"), end_year = structure(c(1356998400, 
1357084800, 1357171200, 1357257600, 1357344000, 1357430400, 1357516800, 
1357603200, 1357689600, 1357776000, 1357862400, 1357948800, 1358035200
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), gbrs = c("LEED", 
"LEED", "LEED", "BREEAM", "LEED", "LEED", "LEED", "BREEAM", "LEED", 
"LEED", "LEED", "BREEAM", "LEED"), indicator = c("Energy & Atmosphere", 
"Energy & Atmosphere", "Energy & Atmosphere", "Health and Wellbeing", 
"Indoor Environmental Quality", "Indoor Environmental Quality", 
"Indoor Environmental Quality", "Management", "Material & Resources", 
"Material & Resources", "Sustainable Sites", "Transport", "Water Efficiency"
), abb = c("EaA", "EaA", "EaA", "HaW", "IEQ", "IEQ", "IEQ", "M", 
"MaR", "Apr", "SS", "T", "WE")), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -13L))

here is what i did

vistime(test, col.event = "abb", col.group = "gbrs", 
        col.start = "start_year", col.end = "end_year", col.tooltip = "tooltip",
        optimize_y = TRUE, show_labels = TRUE)

when i tried adding scale_x_date (below), an error occurs saying NULL

vistime(test, col.event = "abb", col.group = "gbrs", 
        col.start = "start_year", col.end = "end_year", col.tooltip = "tooltip",
        optimize_y = TRUE, show_labels = TRUE) +
  scale_x_continuous(breaks = function(x) exec(seq, !!!x), 
                     labels = function(x) x, 
                     limits = c(2004, 2020))

did i do something wrong? a help would be greatly appreciated! :)


Solution

  • You could instead use the gg_vistime to use ggplot2 functions. For that, we can use the scale_x_datetime function with date_breaks of 1 year like this:

    library(vistime)
    library(ggplot2)
    gg_vistime(test, col.event = "abb", col.group = "gbrs", 
            col.start = "start_year", col.end = "end_year", col.tooltip = "tooltip",
            optimize_y = TRUE, show_labels = TRUE) +
      scale_x_datetime(date_breaks = "1 year", date_labels = "%Y")
    

    Created on 2024-05-06 with reprex v2.1.0