4

我目前正在尝试生成 NOAA 潮汐预测图表(x = 日期时间,y = 水位),其中黎明/日出/黄昏/日落时间作为沿 x 轴时间线的垂直线。

rnoaa 包调用数据并在 POSIXct 中给我预测日期时间。suncalc 库以 POSIXct 格式为我提供了一个数据框,其中包含范围的日出、日落等中的每个日期。

library(rnoaa)
library(tidyverse)
library(ggplot2)
library(suncalc)
march.tides <- as.data.frame(coops_search(station_name = 8551762, 
                                          begin_date = 20200301, end_date = 20200331, 
                                          datum = "mtl", product = "predictions"))
march.tides <- march.tides %>%
  mutate(yyyy.mm.dd = as.Date(predictions.t))
dates <- unique(march.tides$yyyy.mm.dd)
sunlight.times <- getSunlightTimes(date = seq.Date(as.Date("2020/3/1"), as.Date("2020/3/31"), by = 1), 
                lat = 39.5817, lon = -75.5883, tz = "EST")

然后我有一个循环,为每个日历日期吐出单独的图 - 这很有效。垂直线绘制在图表上没有错误,但肯定是在错误的位置(日出是在上午 11 点左右绘制的,应该是 06:30)。

for (i in seq_along(dates)) {
  plot <- ggplot(subset(march.tides, march.tides$yyyy.mm.dd==dates[i])) +
    aes(x = predictions.t, y = predictions.v) +
    geom_line(size = 1L, colour = "#0c4c8a") +
    theme_bw() + 
    geom_vline(xintercept = sunlight.times$sunrise) +
    geom_vline(xintercept = sunlight.times$sunset) +
    geom_vline(xintercept = sunlight.times$dawn, linetype="dotted") +
    geom_vline(xintercept = sunlight.times$dusk, linetype="dotted") +
    ggtitle(dates[i])
  print(plot)
}

我也可以选择单独的日期而不是这种循环方法。即使我将数据子集到单个日期,垂直线仍然没有正确绘制。

我想知道问题是否与时区有关。如果我尝试将时区参数粘贴到潮汐预测数据调用上,我会收到错误消息:

Error in if (!repeated && grepl("%[[:xdigit:]]{2}", URL, useBytes = TRUE)) return(URL) : 
  missing value where TRUE/FALSE needed
4

1 回答 1

2

看起来您想EST用作您的时区,因此您可以将predictions.t.

ggplot我会在using中明确说明您希望在 xaxis 上标记的内容scale_x_datetime,包括时区。

library(rnoaa)
library(tidyverse)
library(ggplot2)
library(suncalc)
library(scales)

march.tides <- as.data.frame(coops_search(station_name = 8551762, 
                                          begin_date = 20200301, end_date = 20200331, 
                                          datum = "mtl", product = "predictions"))

march.tides <- march.tides %>%
  mutate(yyyy.mm.dd = as.Date(predictions.t, tz = "EST"))
dates <- unique(march.tides$yyyy.mm.dd)
sunlight.times <- getSunlightTimes(date = seq.Date(as.Date("2020/3/1"), as.Date("2020/3/31"), by = 1), 
                                   lat = 39.5817, lon = -75.5883, tz = "EST")

for (i in seq_along(dates)) {
  plot <- ggplot(subset(march.tides, march.tides$yyyy.mm.dd==dates[i])) +
    aes(x = predictions.t, y = predictions.v) +
    geom_line(size = 1L, colour = "#0c4c8a") +
    theme_bw() + 
    geom_vline(xintercept = sunlight.times$sunrise) +
    geom_vline(xintercept = sunlight.times$sunset) +
    geom_vline(xintercept = sunlight.times$dawn, linetype="dotted") +
    geom_vline(xintercept = sunlight.times$dusk, linetype="dotted") +
    ggtitle(dates[i]) +
    scale_x_datetime(labels = date_format("%b %d %H:%M", tz = "EST"))
  print(plot)
}

阴谋

带有 xaxis 日期刻度和时区的潮汐图

于 2020-02-29T19:39:34.653 回答