我有一個 GAM 模型,其中一天中的時間是預測值之一。時間是數字格式,因為據我所知,mgcv::gam不接受 POSIXct 類。該模型作業正常,但我希望看到一個圖,其中平滑效果在 X 軸上具有 HH:MM,而不是連續的 UNIX 紀元。我mgcViz用于繪圖。
我怎樣才能在 X 軸標簽上獲得漂亮的時間格式 (HH/HH:MM)?
可重現的例子:
require(mgcv)
require(mgcViz)
min_datetime <- as.POSIXct(strptime("2021-12-27 06:00:00", "%Y-%m-%d %H:%M:%S"))
max_datetime <- as.POSIXct(strptime("2021-12-27 18:00:00", "%Y-%m-%d %H:%M:%S"))
x <- runif(100)
y <- runif(100)
tod <- runif(100, min = as.numeric(min_datetime), max = as.numeric(max_datetime))
df <- data.frame(x, y, tod)
mod <- gam(y ~ x tod, data = df)
viz_mod <- getViz(mod)
plot_mod <- plot(viz_mod, select = 2)
l_fitLine(linetype = 1)
# Epoch on X-axis, should be HH:MM
print(plot_mod)
uj5u.com熱心網友回復:
由于mgcViz是圍繞 的包裝器ggplot2,因此您可以使用標準ggplot2::scale_...函式來操作您的標簽、中斷或任何您想要在圖中顯示的內容。在這里,我們可以使用scale_x_continuous將數字x軸轉換回POSIXct,然后根據需要對其進行格式化。
plot_mod
scale_x_continuous(labels = ~ format(as.POSIXct(.x, origin = origin), "%H:%M"))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/381227.html
上一篇:ggplot2多線樣條平滑
