ggplot2timevisualizationclockhour

Data visualisation with 24hour format


I am trying to make a ggplot, geom point of emergence time of fish, which most likely only emerge between 6pm to 6am. In the x axis would be the date, and Y axis would be the time (hour) of emergence. I use this code which works perfectly :

ggplot(individu, aes(x = Date, y = HRS)) +     
geom_point(alpha = 0.6, color = "black") +     
scale_y_continuous(breaks = 0:23, labels = paste0(0:23, "h")) +     
labs( x = "Date", y = "Emergence time (24h)", title = "Emergence time") +     
theme_minimal() +     
theme(axis.text.x = element_text(angle = 45, hjust = 1))

But it shows overall time from 0 to 23 (11pm) with the arrangement in y-axis starting from 0,1,2,3,4,...23. What is the code if I want the y-axis value starting from 18,19,20,21,22,23,0, 1, 2, 3, 4, 5, 6 (following this order) ?

I tried this code, but it doesnt show the looks that I want, the y-axis value still starting from 0 to 23.

`ggplot(individu, aes(x = Date, y = HRS)) +
geom_point(alpha = 0.6, color = "black") +
scale_y_continuous(
breaks = c(19:23, 0:7),
labels = c(19:23, 0:7) %% 24) +
labs( x = "Date", y = "Emergence time (24h)", title = "Emergence time") +
theme_minimal() +
theme(axis.text.x =  element_text(angle = 45, hjust = 1))`

Solution

  • I think it would work if you introduced the "hours" variable as an ordered factor.

    individu <- data.frame(Date = c(as.Date("2024-05-16"),
                                as.Date("2024-05-17"),
                                as.Date("2024-05-18")),
                       HRS = c(23, 6, 18))
    
    
    individu$HRS <- factor(individu$HRS,
                       levels = c(18:23, 0:6),
                       labels = paste(c(18:23, 0:6), "h"))
    
    
    ggplot(individu, aes(x = Date, y = HRS)) +     
    geom_point(alpha = 0.6, color = "black") +     
    labs( x = "Date", y = "Emergence time (24h)", title = "Emergence time") + 
    theme_minimal() +     
    theme(axis.text.x = element_text(angle = 45, hjust = 1))
    

    I tried it out and it worked for me :)