【问题标题】:Timestamp on x-axis in timeseries ggplot时间序列ggplot中x轴上的时间戳
【发布时间】:2019-01-28 19:13:29
【问题描述】:

我有过去几个月的测量数据:

变量

 x <- df$DatoTid
 y <- df$Partikler
 color <- df$Opgave

我正在尝试根据时间戳绘制我的数据,以便在 x 轴上显示一天中的小时数,而不是特定的 POSIXct 日期时间。 我希望 x 轴的标签和刻度为 fx“00:00”、“01:00”、...“24:00”。 所以中午在x轴的中间。

到目前为止,我尝试将日期时间值转换为字符。 看起来还不太好(您可以看到轴刻度和标签都消失了。可能还有其他问题)。

有人可以帮助我吗? 请让我知道如何为您上传数据。我不知道如何添加一个巨大的 .csv 文件....

# Rounding up to nearest 10 min: 
head(df)
df$Tid2 <- format(strptime("1970-01-01", "%Y-%m-%d", tz="CET") + 
round(as.numeric(df$DatoTid)/300)*300 + 3600, "%Y-%m-%d %H:%M:%S")
head(df)
df$Tid2 <- as.character(df$Tid2)
str(df)

x <- df$Tid2
y <- df$Partikler
color <- df$Opgave

plot2 <- ggplot(data = df, aes(x = x, y = y, color = color)) +
  geom_point(shape=16, alpha=0.6, size=1.8) +
  scale_y_continuous(labels=function(x) format(x, big.mark = ".", decimal.mark = ",", scientific = FALSE)) +
  scale_x_discrete(breaks=c("00:00:00", "06:00:00", "09:00:00", "12:00:00", "18:00:00", "21:00:00")) +
  scale_color_discrete(name = "Case") +
  xlab(" ") +
  ylab(expression(paste("Partikelkoncentration [pt/cc]"))) +
  myTheme + 
  theme(legend.text=element_text(size=8), legend.title=element_text(size=8))
plot2

【问题讨论】:

    标签: r ggplot2 timestamp time-series


    【解决方案1】:

    我会通过创建一个使用一天的新时间戳来解决此问题,但使用现有时间戳的小时/分钟/秒。

    首先,这是您的数据的虚构版本,这里使用Partikler 中的线性趋势:

    library(tidyverse); library(lubridate)
    df <- data_frame(Tid2 = seq.POSIXt(from = ymd_h(2019010100), 
                                       to = ymd_h(2019011500), by = 60*60),
                     Partikler = seq(from = 0, to = 2.5E5, along.with = Tid2),
                     Opgave = as.factor(floor_date(Tid2, "3 days")))
    
    # Here's a plot that's structurally similar to yours:
    ggplot(df, aes(Tid2, Partikler, col = Opgave)) + 
      geom_point() +
      scale_color_discrete(name = "Case")
    

    现在,如果我们将时间戳更改为同一天,我们可以像往常一样在 ggplot 中控制它们,但它们会折叠成一天的时间。我们还可以更改 x 轴,使其不提及时间戳的日期部分:

    df2 <- df %>%
      mutate(Tid2_sameday = ymd_hms(paste(Sys.Date(), 
                                          hour(Tid2), minute(Tid2), second(Tid2))))
    
    
    ggplot(df2, aes(Tid2_sameday, Partikler, col = Opgave)) + 
      geom_point() +
      scale_color_discrete(name = "Case")  +
      scale_x_datetime(date_labels = "%H:%M")
    

    【讨论】:

    • 工作就像一个魅力!谢谢!!
    猜你喜欢
    • 2020-07-01
    • 2021-06-10
    • 1970-01-01
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2015-08-13
    相关资源
    最近更新 更多