r - x 轴作为周数,辅助 x 轴作为日期
问题描述
我正在尝试在 ggplot 中绘制一个时间序列,其中主要 x 轴作为数字,次要 x 轴作为日期。这是我可怜的尝试。
library(tidyverse)
tibble::tribble(
~date, ~ndvi,
"2020-05-18", 0.7655,
"2020-06-14", 0.723,
"2020-07-12", 0.6178,
"2020-08-21", 0.437,
"2020-09-07", 0.4763,
"2020-09-10", 0.4928,
"2020-09-12", 0.4831,
"2020-09-22", 0.4774,
"2020-10-02", 0.5794,
"2020-10-07", 0.606
) %>%
mutate(date = lubridate::ymd(date),
weeks = difftime(date, min(date), units="weeks")) %>%
ggplot(aes(weeks, ndvi)) +
geom_line()+
scale_x_datetime(
sec.axis = dup_axis(name = "", #breaks = date,
labels = scales::time_format("%b")))
#> Error: Invalid input: time_trans works with objects of class POSIXct only
这是所需的输出,其中主要 x 轴有几周,次要 x 轴有时间序列的月份
解决方案
分别为两个 x 轴设置标签。也请检查这个讨论
library(tidyverse)
mydat <- tibble::tribble(
~date, ~ndvi,
"2020-05-18", 0.7655,
"2020-06-14", 0.723,
"2020-07-12", 0.6178,
"2020-08-21", 0.437,
"2020-09-07", 0.4763,
"2020-09-10", 0.4928,
"2020-09-12", 0.4831,
"2020-09-22", 0.4774,
"2020-10-02", 0.5794,
"2020-10-07", 0.606
) %>%
mutate(date = lubridate::ymd(date),
weeks = as.numeric(difftime(date, min(date), units="weeks")))
mydat %>%
ggplot(aes(date, ndvi)) +
geom_line() +
scale_x_date(date_breaks = "4 weeks", labels = scales::date_format("%W"),
sec.axis = dup_axis(name = "", labels = scales::date_format("%b")))
由reprex 包于 2021-02-10 创建(v1.0.0)
推荐阅读
- python - Dash plotly 在计算之间更新标签
- node.js - Socket.io 或 node js 中是否有函数可以观察 API 输出的变化?
- sql - 驱动将 uint64 参数转换为 int32 负值
- c++ - C++ gRPC TCP错误协议不可用
- c# - 无法使用自动映射器从链接表中获取数据
- sql - Oracle查询以获取同一表中具有重复列集的所有行
- c# - 如何在 C# 中使用 Rijndael 加密参数?
- python - python安装问题(app Dash & WSGI server)
- visual-studio - 是否可以运行已经构建的容器而不是创建构建的容器?
- javascript - React context dispatch 状态改变后如何处理