Search code examples
rgraph

R studio set x axis by year values


I need to draw the following graph:

On X axis I have 72 values which represents the months from 2015 to 2020. On Y axis I can have value from 0 to 5.

This is my code with x values divided in wrong way:

yval=round(runif(72, 0, 5))
plot(yval, type="l", col="red")

This is my output

I would like to see my x axis divided by year values, in my case: 2015,2016,2017,2018,2019,2020

  • 2015 in position 0,
  • 2016 in position 12,
  • 2017 in position 24,
  • 2018 in position 32,
  • 2019 in position 48,
  • 2020 in position 60
  • And no other values.

Something like the x axis of the following graph: enter image description here

How can I do this?


Solution

  • Use xaxt="n' to disable the automatic axis labeling, and axis(.) to add your own.

    plot(yval, type="l", col="red", xaxt="n")
    axis(1, c(0,12,24,36,48,60), 2015:2020)
    

    enter image description here

    (BTW, I changed 32 to 36, I thought it would align better :-)