jeffpkamp jeffpkamp - 3 months ago 10
R Question

Keeping American Style dates in numeric order in R

I am trying to make a simple graph of high and low temperatures over a month. The data comes from a table with this format.

Date High Low
8/1/2016 84 78
8/2/2016 83 79
8/3/2016 93 57
8/4/2016 94 68
8/5/2016 99 75
8/6/2016 82 78
8/7/2016 88 57
8/8/2016 100 58
8/9/2016 92 68
8/10/2016 84 55
8/11/2016 85 55
8/12/2016 96 56
8/13/2016 85 71
8/14/2016 74 66
8/15/2016 73 53
8/16/2016 93 79
8/17/2016 86 71
8/18/2016 90 70
8/19/2016 71 51
8/20/2016 87 53
8/21/2016 96 66
8/22/2016 70 66
8/23/2016 81 71
8/24/2016 77 76
8/25/2016 83 65
8/26/2016 82 64
8/27/2016 78 52
8/28/2016 86 61
8/29/2016 81 50
8/30/2016 95 53
8/31/2016 92 56


I plot like so:

data=read.table('data location', header=1)
plot(data[,1],data[,2])
lines(data[,1],data[,2])


ploted data

when I look at the date data frame i get the following

data[,1]
[1] 8/1/2016 8/2/2016 8/3/2016 8/4/2016 8/5/2016 8/6/2016 8/7/2016 8/8/2016 8/9/2016 8/10/2016 8/11/2016 8/12/2016 8/13/2016 8/14/2016 8/15/2016 8/16/2016 8/17/2016 8/18/2016
[19] 8/19/2016 8/20/2016 8/21/2016 8/22/2016 8/23/2016 8/24/2016 8/25/2016 8/26/2016 8/27/2016 8/28/2016 8/29/2016 8/30/2016 8/31/2016
31 Levels: 8/1/2016 8/10/2016 8/11/2016 8/12/2016 8/13/2016 8/14/2016 8/15/2016 8/16/2016 8/17/2016 8/18/2016 8/19/2016 8/2/2016 8/20/2016 8/21/2016 8/22/2016 8/23/2016 ... 8/9/2016


The Levels at the bottom are clearly sorting the data in an alphabetical format and not a numerical format.... I've tried converting it with
as.character.date
but then it will not plot with it, complaining about infinite xlim values.

Answer

It is better to convert to Date class

data$Date <- as.Date(data$Date, "%m/%d/%Y")
plot(data[,1],data[,2])
lines(data[,1],data[,2])

If we need the original format for 'Date' in the plot, then we can set xaxt="n" in the plot and change the tick labels with axis

plot(data[,1],data[,2], xaxt = "n")
lines(data[,1],data[,2])
axis(1, data[,1], format(data[,1], "%m/%d/%Y"))