在 ggplot 2 的 x 轴上将时间从分钟缩放到小时

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

我正在尝试更改 ggplot 中的 x 轴,因为时间无法显示。正如您在图中看到的那样,有一条黑线而不是时间。

我不想显示每分钟而是每小时!这是我的数据:DLR data。我收到以下错误消息:

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")))

你可以使用

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")))

哪个returns

我使用的主要区别:

  • 正在创建 Time = as.POSIXct(strptime(V1, "%d-%B-%Y %H:%M:%S"))。这会导致您的 time_trans-error.
  • 将 x 轴标签旋转 90 度
  • 将所有内容放入 dplyr 管道中。