【问题标题】:How to include ticks for every date using ggplot?如何使用ggplot包含每个日期的刻度?
【发布时间】:2021-05-21 07:51:58
【问题描述】:

让我们考虑数据:

x <- c(
  "1900-01-01", "1900-04-01", "1900-07-01", "1900-10-01", "1901-02-01",
  "1901-05-01", "1901-08-01",
  "1901-11-01", "1902-02-01", "1902-05-01", "1902-08-01", "1902-11-01", "1903-02-01"
)
x <- as.Date(x)
y <- 1:length(x)
df <- data.frame("Date" = x, "Preds" = y) 

我想使用ggplot 制作一个绘图,但标记每个日期(格式为%M-%Y):

到目前为止我的工作:

ggplot(df, aes(x = Date, y = Preds)) +
  geom_line() +
  scale_x_date(date_breaks = "3 month", date_labels = "%b-%Y")

但是这段代码带来了一个问题:开始日期是二月,而我们的日期是一月开始。

你知道我怎样才能把时间倒退一个月吗?我是否必须明确说明我想在三个月前休息一下?或者是否有任何通用解决方案可以让我在没有此规范的情况下只为每个日期打勾?

【问题讨论】:

    标签: r date ggplot2


    【解决方案1】:

    我们只需要包含breaks = x:

    ggplot(df, aes(x = Date, y = Preds)) +
      geom_line() +
      scale_x_date(breaks = x, date_labels = "%b-%Y")
    

    【讨论】:

      猜你喜欢
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 2017-06-07
      • 2021-04-01
      相关资源
      最近更新 更多