【问题标题】:ggplot2 in R: How to change starting / ending point for date axis?R中的ggplot2:如何更改日期轴的起点/终点?
【发布时间】:2021-05-24 00:25:30
【问题描述】:

我正在尝试重新创建以下情节。

但不管我做什么,我的 X 轴标记都是从 1965 年开始的,而不是 1963 年。这是我得到的图表。

这是我的代码:

ggplot(dulles, aes(Index, Passengers)) + 
  geom_line() + 
  geom_point(color = "red") + 
  ylim(0, 25000) + 
  scale_x_date(limits = as.Date(c("1963", "2015"), format = "%Y"), date_breaks = "5 years", date_labels = "%Y")

如您所见,我设置了限制参数,但它们没有显示出来。

我还尝试将date_breaks = "5 years", date_labels = "%Y") 替换为breaks = as.Date(as.character(seq(1963, 2015, 5)), format = "%Y"),无论如何这可能很愚蠢。

我希望 X 轴标签从 1963 年开始到 2013 年结束,但不删除 2014 年和 2015 年的数据点,就像在原始图中一样。

我该怎么做?

【问题讨论】:

  • 请发布数据。或者在哪里可以找到数据集dulles。
  • @RuiBarradas 这是链接:gofile.io/d/nr01t2 这是我用来将数据加载到 R 中的代码:dulles <- read_excel("./Dulles_2-2.xlsx") dulles <- as.xts(dulles[,-1], order.by = as.Date(dulles$Year,format = "%Y"))

标签: r date xts


【解决方案1】:

定义断点向量是一种强制轴刻度线的简单方法。

library(ggplot2)

breaks.vec <- seq(min(df1$Index), max(df1$Index), by = "5 years")

ggplot(df1, aes(Index, Y)) + 
  geom_line() + 
  geom_point(color = "red") + 
  scale_x_date(breaks = breaks.vec, date_labels = "%Y")

测试数据创建代码

set.seed(2021)
Index <- seq(as.Date("1963-01-01"), as.Date("2015-12-31"), by = "1 years")
Y <- cumsum(rnorm(length(Index)))
df1 <- data.frame(Index, Y)

【讨论】:

  • 非常感谢!那完全奏效了。 scale_x_date(name = "Year", date_labels = "%Y", breaks = seq(min(index(dulles)), max(index(dulles)), by = "5 years")) 是我使用的新代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 2018-02-08
相关资源
最近更新 更多