David Resch
David Resch

Reputation: 113

Changing values of x-axis on my graph in R

My graph has on the y-axis numerical values of my data which is the level of depression and on the the x-axis I have order (numbers from 1-40 because I have 40 observations) But these are in fact quarters as my data is quarterly (2008-2013). So I would like to change the x-axis from an order of 1-40 to Year and Quarter (e.g. 2008 Q1,2008 Q2,..). I am however not sure how I can do that. Any help is greatly appreciated!

Upvotes: 0

Views: 204

Answers (1)

Mehdi Nellen
Mehdi Nellen

Reputation: 8964

Here's an example with your 40 quarters and starting in 2008:

quarter       <- seq(40)
starting.year <- 2008

#create a function
convertToQ <- function(qs, s) {
  d <- c()
  for(q in qs){
    qtr <- (q-1)%%4 +1
    d <- c(d, (paste(s, " Q", qtr, sep = "")))
    if(qtr == 4) s <- s +1
  }
  return(d)
}

# generate data frame
data <- data.frame(depression = runif(40, -5.0, 5.0),
                   quarters   = convertToQ(quarter, starting.year),
                   stringsAsFactors=FALSE)

# plot
ggplot(data, aes(x = quarters, y = depression)) +
  geom_point() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

This produces the following plot: quarter years ggplot geom point

Upvotes: 1

Related Questions