ggplot2 - 水平轴上的时间

问题描述 投票:0回答:1

我正在尝试使用 R 中的 ggplot2 绘制图表。我面临的问题是,在水平轴(即时间轴)上仅出现年份,而不是日期(季度),具体来说,仅出现几年,即2000年、2010年、2020年。

我一直在使用的代码如下,我得到的结果附在照片中。ggplot2 graph。您可以使用我使用的数据运行我的代码,这些数据可以在以下链接中找到:https://www.dropbox.com/scl/fo/fje18n63wqkqepy5knikq/ADX_A5mD_q98bMCmIAz8Zl8?rlkey=99a7pmsovlsyekw7g5b36s9kc&dl=0

require(ggplot2)
df <- as.data.frame(data_for_use[, 1:18])

ggplot(df, aes(x = date, y = `Inflation spillovers`))+
            geom_area(fill = "4",     # colour of area
            alpha = 0.2,  # transparency of the area
            color ="red2" ,    # Line color
            lwd = 1.5,    # Line width
            linetype = 1)+ # Line type
            ylim(0, 125)+
            theme_light(base_size=15)

我的问题是如何使更多日期出现在横轴上,而不是只有三年(2000年、2010年、2020年),以及如何更改格式(季度或每月,而不仅仅是年份)。

date ggplot2 format
1个回答
0
投票

几个选项:

  1. 使用
    scale_x_date
    设置日期格式(参见第一幅图)
  2. 将日期转换为
    yearquarter
    并使用
    scale_x_yearquarter
    (第二个图)

在这两种情况下,您都可以控制休息次数。

library(tidyverse)

df <- tibble(
  date = seq(ymd("2000-01-01"), ymd(today()), by = "day"),
  inflation_spillovers = rep(seq(20, 125, 0.01), length.out = 8864)
)

ggplot(df, aes(x = date, y = inflation_spillovers)) +
  geom_area(
    fill = "4",
    alpha = 0.2,
    color = "red2",
    lwd = 1.5,
    linetype = 1
  ) +
  ylim(0, 125) +
  theme_light(base_size = 15) +
  scale_x_date(date_labels = "%Y %b", date_breaks = "1 year") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))


library(tsibble)

df |> 
  mutate(date = yearquarter(date)) |> 
  ggplot(aes(x = date, y = inflation_spillovers)) +
  geom_area(
    fill = "4",
    alpha = 0.2,
    color = "red2",
    lwd = 1.5,
    linetype = 1
  ) +
  ylim(0, 125) +
  theme_light(base_size = 15) +
  scale_x_yearquarter(date_breaks = "1 year") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

创建于 2024-04-07,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.