2015-03-13 12 views
5

Per il seguente codice di esempio:formattazione X etichetta dell'asse in R per una condizione specifica

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) 

Ho la seguente tabella:

enter image description here

Quello che voglio è quando cambia il mese, Voglio essere in grado di aggiungere il nome del mese sotto il giorno sull'asse x. Quindi, in questo esempio, quando diventa 01, dovrebbe mostrare 01 Mar (marcia su una riga separata)

risposta

2

Può succedere se fai qualcosa di simile a questo:

i dati oltre il mese vettore:

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 

Soluzione:

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) 

Fino a qui è solo il vostro codice. Ora è necessario aggiungere un nuovo asse, impostare il colore dell'asse al bianco e tracciare il vettore mese creato in precedenza:

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') 

Il risultato assomiglia a quello che hai chiesto:

enter image description here

Problemi correlati