Home > Software design >  Plot quarterly data and specify quarters using ggplot in rstudio
Plot quarterly data and specify quarters using ggplot in rstudio

Time:06-13

I want to plot quarterly data, where the information is saved in the variable yq as: YYYY Q (e..g 2007 Q1), I created by combining Year and Quarter (1, 2, 3, 4):

df$yq = as.yearqtr(paste(df$Year, df$Quarter), "%Y %q")

Looking around on the examples online, I wrote this code but the problem is that it does not let me specify the years I want to display on the x-axis - or rather I can't seem to find a way to apply the breaks for this type of data. I have 15 years of data and would like to only display the label every 3 years, so that the only labels are 2005.Q1, 2008.Q1, 2011.Q1, 2014.Q1, 2017.Q1.

Grateful for tips!

plot = ggplot(df, aes(x = yq, y = rate, color = "red"))  
  geom_point()  
  geom_line(aes(y = lin, color = "green"), size = 1)  
  geom_line(aes(y = quad, color = "brown"), size = 1)  
  geom_line(aes(y = cube, color = "blue"), size = 1)  
  geom_line(aes(y = log, color = "pink"), size = 1)  
  geom_line(aes(y = power_corr, color = "black"), size = 1)  
  geom_line(aes(y = exp_corr, color = "yellow"), size = 1)  
  scale_color_identity(name = "Models",
                       breaks = c("red", "green", "brown", "blue", "pink", "black", "yellow"),
                       labels = c("Observed", "Linear", "Quadratic", "Cubic", "Log", "Power", "Exponential"),
                       guide = "legend")

plot   
theme(panel.grid.major = element_blank(), 
      panel.grid.minor = element_blank(), 
      panel.background = element_blank(), 
      axis.line = element_line(colour = "black")) 
  theme(axis.text.x = element_text(size = 8, angle=-45, hjust = 0.001), 
        legend.key = element_rect(color = NA, fill = NA)) 
  labs(title="", x = "Year/quarters", y = "Smoking prevalence") 
  scale_x_yearqtr(format='%Y.Q%q')

CodePudding user response:

The data was not provided so we will use a simple example of x and y vectors and use scale_x_yearqtr with the indicated breaks and format arguments.

library(ggplot2)
library(zoo)

# inputs
x <- as.yearqtr(2000)   0:29
y <- 1:30

qplot(x, y)   
  scale_x_yearqtr(breaks = seq(min(x), max(x), by = 3), format = "%Y.Q%q")
  • Related