【问题标题】:Scale the time from minutes to hours on the x-axis in ggplot 2在ggplot 2中的x轴上将时间从几分钟缩放到几小时
【发布时间】:2021-07-25 21:04:49
【问题描述】:

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

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

错误:输入无效:time_trans 仅适用于 POSIXct 类的对象。 我怎么解决这个问题?提前致谢!

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

【问题讨论】:

  • 请发送reproducible example。使用dput(head(dlr_june_2020)) 显示部分数据。请编辑您的问题并将这些数据放在那里。
  • 请修正两个拼写错误:read.csv2() 函数末尾有一个',而breaks = date_breaks("1 hour) 缺少一个"。我不喜欢编辑有问题的代码,所以我不会自己做。
  • 非常感谢!
  • 您正在加载library(readr),但实际上您使用的是来自base Rread.csv2。也许您想使用read_csv2

标签: r ggplot2 scale


【解决方案1】:

你可以使用

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

返回

我使用的主要区别:

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

【讨论】:

    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多