簡體   English   中英

如何使用ggplot調整x軸上的時間?

[英]How to adjust the time on x-axis with ggplot?

我正在嘗試使用 ggplot 進行 plot(時間 VS 速度和降水),但我得到了一個凌亂的 plot。 數據低於(df),然后是我嘗試過的代碼。

    df <- structure(list(Agency.Station.ID = c("MI270N003.6D", "MI270N004.7D", 
"MI270N005.7D", "MI270N007.3D", "MI270N008.5D", "MI270N003.6D", 
"MI270N004.7D", "MI270N005.7D", "MI270N007.3D", "MI270N008.5D", 
"MI270N003.6D", "MI270N004.7D", "MI270N005.7D", "MI270N007.3D", 
"MI270N008.5D", "MI270N003.6D", "MI270N004.7D", "MI270N005.7D", 
"MI270N007.3D", "MI270N008.5D"), date_time = structure(c(1427846400, 
1427846400, 1427846400, 1427846400, 1427846400, 1427846700, 1427846700, 
1427846700, 1427846700, 1427846700, 1427847000, 1427847000, 1427847000, 
1427847000, 1427847000, 1427847300, 1427847300, 1427847300, 1427847300, 
1427847300), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    Date = structure(c(16526, 16526, 16526, 16526, 16526, 16526, 
    16526, 16526, 16526, 16526, 16526, 16526, 16526, 16526, 16526, 
    16526, 16526, 16526, 16526, 16526), class = "Date"), Time = c("00:00:00", 
    "00:00:00", "00:00:00", "00:00:00", "00:00:00", "00:05:00", 
    "00:05:00", "00:05:00", "00:05:00", "00:05:00", "00:10:00", 
    "00:10:00", "00:10:00", "00:10:00", "00:10:00", "00:15:00", 
    "00:15:00", "00:15:00", "00:15:00", "00:15:00"), Speed = c(59, 
    34, 46, 61, 46, 58, 39, 51, 36, 52, 62, 47, 49, 57, 50, 59, 
    50, 35, 54, 44), Precipitation = c(0, 0, 0, 0, 0, 0, 0, 0, 
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA, 20L
), class = "data.frame")

這是我嘗試過的代碼:

df <- df %>% gather(Aspect, Value, -Agency.Station.ID, -Date, -Time)
df$Agency.Station.ID <- factor(df$Agency.Station.ID)
df$Date <- factor(df$Date)
for(i in levels(df$Agency.Station.ID)) {
  pdf(paste0(i,'.pdf'))

  for(j in levels(df$Date)) {
    subset.data <- df[which(df$Agency.Station.ID==i & df$Date==j),]
    if (nrow(subset.data)!=0) {
      p <- ggplot(data=subset.data, aes(Time, Value, group = 1)) +
        geom_line(aes(color=Aspect)) +
        labs(title=paste('Station:',i, " Date:",j)) +
        theme_bw()
      invisible(print(p))
    }
  }
  dev.off()
}

我擔心的是時間(我每天有 288 次觀察),因為它將在 x 軸上壓縮。 我的輸出看起來如何

您可以組合以下內容,而不是將Date Time存儲在單獨的列中:

df$Datetime <- as.POSIXct(paste0(df$Date, df$Time))

現在ggplot在 x 軸上打印所有標簽,因為Timecharacter形式給出。 ggplot調用函數來prettify軸標簽,即打印信息豐富、不重疊的標簽。 但是,這需要numeric變量的變化,例如R的日期時間表示POSIXct

PS:您的示例對我不起作用,缺少Aspect

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM