Search code examples
rggplot2scale

Scale the time from minutes to hours on the x-axis in ggplot 2


I am trying to change the x-axis in my ggplot because the times cannot be displayed visibly. As you can see in the graph there is a black line instead of the times.

enter image description here

I don't want to display every minute but every hour! Here are my data: DLR data. I have the following error message:

Error: Invalid input: time_trans works with objects of class POSIXct only. How can I solve this problem? Thanks in advance!

library(ggplot2)
library(read.dbc)
library(readr)
library(scales)

#read ASCII
dlr_june_2020 = read.csv2("C:/Users/cathe/OneDrive/Desktop/DWD/dlr_june_2020.dat", 
                          header = FALSE, sep = ";")

#as.numeric
Watt_pro_m2 <- as.numeric(dlr_june_2020$V2)
Time <- dlr_june_2020$V1

#function scale_x_time
dlr_june_2020$V1=strptime(dlr_june_2020$V1, "%Y-%m-%d %H:%M:%S")

ggplot(data = dlr_june_2020, aes(V1, Watt_pro_m2)) +
  geom_point(colour = "red", size = 0.5)+
  ggtitle("Langwellige atmosphärische Gegenstrahlung (02. Juni 2020)")+
  scale_y_continuous(breaks = c(0,50,100,150,200,250,300,350,400), limits = c(0,500))+
  scale_x_datetime(breaks = date_breaks("1 hour"),labels=date_format("%H:%M")) +
  theme(axis.text=element_text(size=8),
      axis.title=element_text(size=10))+
  labs(x= "Minuten", y= "Watt/m2") +
  theme(axis.title.y = element_text(margin = margin(r = .5, unit = "cm"))) +
  theme(axis.title.x = element_text(margin = margin(t = .5, unit = "cm")))

Solution

  • You could use

    library(dplyr)
    library(ggplot2)
    library(scales)
    
    dlr_june_2020 %>% 
      tibble() %>% 
      mutate(Watt_pro_m2 = as.numeric(V2),
             Time = as.POSIXct(strptime(V1, "%d-%B-%Y %H:%M:%S"))) %>%  
      ggplot(aes(Time, Watt_pro_m2)) +
      geom_point(colour = "red", size = 0.5)+
      ggtitle("Langwellige atmosphärische Gegenstrahlung (02. Juni 2020)")+
      scale_y_continuous(breaks = c(0,50,100,150,200,250,300,350,400), limits = c(0,500))+
      scale_x_datetime(breaks = breaks_width("1 hour"),labels=date_format("%H:%M")) +
      theme(axis.text.x=element_text(size=8, angle = 90),
            axis.text.y=element_text(size=8),
            axis.title=element_text(size=10))+
      labs(x= "Stunden", y= "Watt/m2") +
      theme(axis.title.y = element_text(margin = margin(r = .5, unit = "cm"))) +
      theme(axis.title.x = element_text(margin = margin(t = .5, unit = "cm")))
    

    which returns enter image description here

    The main differences I used:

    • Creating Time = as.POSIXct(strptime(V1, "%d-%B-%Y %H:%M:%S")). This causes your time_trans-error.
    • Rotating the x-axis-label by 90 degrees
    • Putting everything in a dplyr-pipe.