Formatting the X axis label in R for a specific condition

For the following code example:

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 diagram:

enter image description here

What I want, when the month changes, I want to be able to add the name of the month below the day along the x axis. So in this example, when it becomes 01, it should show March 01 (March on a separate line).

+5
source share
1 answer

This can happen if you do something like this:

Your data plus the vector of the month:

 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 

Decision:

 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) 

Before that, only your code. Now you need to add a new axis, set the axis color to white and build 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 ie 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 you requested:

enter image description here

+2
source

Source: https://habr.com/ru/post/1215302/


All Articles