R proposes a special data type for dates. It is important to use it since it make the creation of charts lot easier. Let’s illustrate it. This example is inspired from this webpage that provides lot of explanations.
First we create data. With the str function you can check the type of each column. Dates are recognized as factor.
1 2 3 4 5 6 7 8 9 10 |
# Create data set.seed(124) date=paste( "2015/03/" , sample(seq(1,31),6) , sep="") value=sample(seq(1,100) , 6) data=data.frame(date,value) # Date and time are recognized as factor: str(data) |
We can plot it but the results we observe is quite disapointing.
1 2 3 4 |
# So ploting them works bad --> wrong order, date without value are not represented, plot(data$value~data$date) |
If we switch to a date format and add a little bit of pimpimg, it becomes a better chart!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Let's change the date to the "date" format: data$date=as.Date(data$date) # So we can sort the table: data=data[order(data$date) , ] # and replot --> R now understand how to plot it! plot(data$value~data$date) # Easy to make it better now: plot(data$value~data$date , type="b" , lwd=3 , col=rgb(0.1,0.7,0.1,0.8) , ylab="value of ..." , xlab="date" , bty="l" , pch=20 , cex=4) abline(h=seq(0,100,10) , col="grey", lwd=0.8) |
Not what you are looking for ? Make a new search ![mediatagger]
Leave a Reply
Be the First to Comment!