Search code examples
rggplot2

How to Display Time Labels at X-axis Correctly in R ggplot


I try to plot the data with R ggplot but the time label cannot display at x-axis correctly. Any advice will be greatly appreciated.

Here is what the sample data looks like:

structure(list(activity = c("Running", "Running", "Running", 
"Running", "Running", "Running", "Running", "Running", "Running", 
"Running"), time = structure(c(-2209064400, -2209064100, -2209063800, 
-2209063500, -2209063200, -2209062900, -2209062600, -2209062300, 
-2209062000, -2209061700), tzone = "UTC", class = c("POSIXct", 
"POSIXt")), level = c(0.0450582956975968, 0.049786810752437, 
0.049786810752437, 0.0409378662803991, 0.0373264654807176, 0.0373264654807176, 
0.0518442650051548, 0.0471157499503146, 0.0527766243609182, 0.0615719801782924
)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))

The data can be visualized in Excel correctly.

enter image description here

But I cannot plot the same data right in R. The time labels are not presented appropriately and the data shape looks wrong as well.

enter image description here

Here are the R codes I use:

ggplot(df2, aes(x = time, y = activity)) + geom_density_ridges2()

Solution

  • You need to use scale_x_datetime, with the argument date_labels = "%I:%M %p" to get the same output format as Excel.

    However, geom_density_ridges is the wrong function here. You are graphing the level of each activity in Excel, not the density of measurements across the x axis, which is why the shapes are wrong.

    Using an approximation of your data set as shown in the question with the same basic structure and names, we can reproduce your Excel plots in R as follows:

    library(tidyverse)
    
    df %>%
      mutate(activity = factor(activity, c("Walking", "Running"))) %>%
      ggplot(aes(time, level, color = activity)) + 
      geom_line(linewidth = 1) + 
      facet_wrap(activity ~ ., ncol = 1, scales = "free") +
      scale_x_datetime(date_breaks = "1 hour",
                       date_labels = "%I:%M %p") +
      scale_colour_manual(NULL, values = c("deepskyblue4", "orangered")) +
      labs(x = NULL) +
      theme_bw(16) +
      theme(panel.grid.major.x = element_blank(),
            panel.grid.minor = element_blank(),
            axis.text.x = element_text(hjust = 1, angle = 45),
            strip.background = element_blank(),
            strip.text = element_text(size = 20, face = "bold"))
    

    enter image description here