0

Suppose I have a vector of numbers from 1:12 and want to plot them over period of time ranged from Jan. 2013 to Dec. 2013. I used the following code to generate the data and plotting:

dates<-seq(as.Date("2013/1/1"), by = "month", length.out = 12) 
n<-seq(1:12)
df<-cbind(dates,n)
plot(df)

However, some problems come up with the last code; Firstly could not find an option in the first seq to generate only months and year without day. Secondly, all dates in df become serial even after adding as.Date before dates in cbind. Finally, the x axis in the plot not in the time format as a result of the last two problems.

mallet
  • 2,454
  • 3
  • 37
  • 64

2 Answers2

1
df<-data.frame(dates=dates,n=n)
plot(df$dates, df$n, axes=FALSE)
axis(1, labels=format(df$dates, "%b %Y"), at=df$dates)
axis(2)
1

just use

plot(dates,n)

without cbinding it. cbind creates a matrix (see class(df)). Within this process the dates are saved as class numeric.

enter image description here

For nicer and easier to customize plots use

require(ggplot2)
qplot(dates,n) + xlab("") + ylab("my y lab")

enter image description here

Rentrop
  • 20,979
  • 10
  • 72
  • 100