Panagiotis Palaios
Panagiotis Palaios

Reputation: 13

ggpot2-Time on horizontal axis with multiple lines

I am trying to plot a graph using ggplot2 in R.The variables I want to plot are time series and are more than one (3 variables). The issue I am facing is that on the horizontal axis, namely the axis of time, appear only the year, instead of date (monthly) 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.enter image description here

require(ggplot2)

library(tidyr)
library(dplyr)

#date<-seq(as.Date("1997/1/1"), as.Date("2023/12/1"),by="months")
df <-data_for_use_all_spills %>%
select(date, `TSI (TVP-VAR)`, 'GPR to inflation (TVP-VAR)','CPU to inflation (TVP-VAR)') %>%
  gather(key = "variables", value="value", -date)
head(df, 3)

ggplot(df, aes(x = date, y = value)) + 
  geom_line(aes(color = variables), linewidth = 1) +
  scale_color_manual(values = c("cornflowerblue","orange","red2")) +
  theme_light(base_size=15)+
  labs(y= "Spillover effects", x = "time")
  

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 (monthly, instead of just the year) as well. Thank you in advance!

Upvotes: 0

Views: 37

Answers (2)

Carl
Carl

Reputation: 7540

It's an empty data frame, but illustrates the possibilities re controlling the format, frequency and styling of the x-axis dates:

library(ggplot2)
library(tibble)

df <- tibble(
  date = seq(as.Date("1997/1/1"), as.Date("2023/12/1"), by = "months")
)

ggplot(df, aes(date)) +
  scale_x_date(date_labels = "%Y %b", date_breaks = "1 year") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
  labs(x = NULL)

Created on 2024-04-23 with reprex v2.1.0

Upvotes: 0

vgilbart
vgilbart

Reputation: 91

You should take a look at scale_x_date(). In particular the date_breaks and date_labels parameters.

See the related doc here: https://ggplot2.tidyverse.org/reference/scale_date.html

Upvotes: 0

Related Questions