【问题标题】:ggplot2: force time series x labels on each yearggplot2:每年强制时间序列x标签
【发布时间】:2022-06-29 22:27:48
【问题描述】:

下面我创建了一个可重现的示例图表,范围为 10000 天。如您所见,此图表信息量很大且增值,但它可以作为示例。

我想每年强制一个标签,而不是每 10 年一个 x 标签。如何实现?

library(ggplot2)
library(tidyr)
exdays <- 1:10000
exdata <- sin(exdays)
exdate <- as_date("2022-01-01")+days(exdays)
exdat <- tibble(exdate, exdata)
p1 <- ggplot(exdat, aes(x=exdate, y=exdata)) +
  geom_line(color="darkred", size=0.7) +
  ggtitle("example")
p1

【问题讨论】:

    标签: r ggplot2 time-series


    【解决方案1】:

    这行得通

    p1 <- ggplot(exdat, aes(x=exdate, y=exdata)) +
      geom_line(color="darkred", size=0.7) +
      ggtitle("example") + scale_x_date(date_breaks = "1 year")
    

    【讨论】:

      【解决方案2】:

      您可能希望使用 scale_x_date 和 1 年的 date_breaks 来指定 date_labels

      library(ggplot2)
      library(tidyr)
      exdays <- 1:10000
      exdata <- sin(exdays)
      exdate <- as_date("2022-01-01")+days(exdays)
      exdat <- tibble(exdate, exdata)
      p1 <- ggplot(exdat, aes(x=exdate, y=exdata)) +
        geom_line(color="darkred", size=0.7) +
        scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
        ggtitle("example")
      p1
      

      输出:

      【讨论】:

        猜你喜欢
        • 2023-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-08
        • 2017-01-17
        • 1970-01-01
        相关资源
        最近更新 更多