【问题标题】:x axis as week number and secondary x-axis as datex 轴作为周数,次要 x 轴作为日期
【发布时间】:2021-05-13 17:07:54
【问题描述】:

我正在尝试在 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 轴具有时间序列中的月份

【问题讨论】:

  • 你没有描述你想要的输出。您包含的图像看起来像您的代码生成的当前输出。您能否具体说明您希望更改的内容?
  • scales::time_format("%^b") 似乎是一个错字。 labels = scales::time_format("%b") 按预期工作
  • 感谢@RonakShah,但我认为这不是我的代码的问题

标签: r ggplot2


【解决方案1】:

分别为两个 x 轴设置标签。 Please check also this discussion

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 package (v1.0.0) 于 2021-02-10 创建

【讨论】:

  • 谢谢@tjebo,这真的很有帮助,但是我的问题可能不是很清楚,因为我想在 x 轴上使用新列 weeks
猜你喜欢
  • 2021-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-10
  • 2018-03-21
  • 1970-01-01
  • 2014-04-22
相关资源
最近更新 更多