For the following sample code:
y <- c(23, 34, 11, 9.6, 26, 31, 38, 38, 30, 36, 31)
days <- seq(as.Date("2015-2-25"), by="day", length=11)
n <- length(y)
x <- 1:n
plot(x, y, type='n', xlab="Days", ylab="Y", xaxt='n')
axis(1, at=seq(1,11) ,labels=format(days, "%d"), las=1)
lines(y)
I have the following chart:
What I want is when the month changes, I want to be able to add the month name below the day on the x axis. So in this example, when it becomes 01, it should show 01 Mar (March on a separate line)
It can happen if you do something like this:
Your data plus the month vector:
y <- c(23, 34, 11, 9.6, 26, 31, 38, 38, 30, 36, 31)
days <- seq(as.Date("2015-2-25"), by="day", length=11)
#my addition
#contains the name of the month for where day == '01' else is blank
months <- ifelse(format(days, '%d')=='01', months(days) , '')
n <- length(y)
x <- 1:n
Solution:
plot(x, y, type='n', xlab="Days", ylab="Y", xaxt='n')
axis(1, at=seq(1,11) ,labels=format(days, "%d"), las=1)
lines(y)
Up to here is only your code. Now you need to add a new axis, set the axis colour to white and plot the month vector created above:
par(new=T) #new plot
par(mar=c(4,4,4,2)) #set the margins. Original are 5,4,4,2.
#I only changed the bottom margin i.e. the first number from 5 to 4
#plot the new axis as blank (colour = 'white')
axis(1, at=seq(1,11) ,labels=months, las=1, col='white')
The result looks like what you asked for:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With