Reputation: 13
I am trying to plot a graph using ggplot2 in R. The issue I am facing is that on the horizontal axis, namely the axis of time, appear only the year, instead of date (quarterly) and specifically, only few years, namely 2000, 2010, 2020.
The code I have been using is the following and the result I got is attached as a photo.ggplot2 graph.
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)
My question is how to make more dates appear on the horizontal axis, instead of only three years (2000, 2010, 2020) and how to change the format (quarterly or monthly, instead of just the year) as well.
Upvotes: 1
Views: 53
Reputation: 7540
A couple of options:
scale_x_date
(see first plot)yearquarter
(or yearmonth
) object and use scale_x_yearquarter
(or scale_x_yearmonth
) per the second plot.In both cases you can control the number of breaks.
library(tidyverse)
df <- tibble(
date = seq(ymd("2000-01-01"), ymd(today()), by = "day"),
inflation_spillovers = rep(seq(20, 125, 0.01), length.out = length(date))
)
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)) |>
summarise(inflation_spillovers = last(inflation_spillovers), .by = 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))
Created on 2024-04-08 with reprex v2.1.0
Upvotes: 0