Reputation: 4008
i have the following data frame: dates from 2013-01-01, to 2014-12-31.
Problem: How to plot with plot.ts showing month by month trend?
This is my data frame (just first 6 lines):
date Pedidos
1 2013-01-01 0
2 2013-01-02 0
3 2013-01-03 0
4 2013-01-04 0
5 2013-01-05 0
6 2013-01-06 0
Step 1: Tried to create a ts object with this code
Pedidos_meses_1314 <- ts(df$Pedidos, frequency = 12, start = c(2013,1), end = c(2014,12))
But get this: Note: I do have "pedidos" in 2014. Don't know why it shows "0"s.
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2013 0 0 0 0 0 0 0 0 0 0 0 0
2014 0 0 0 0 0 0 0 0 0 0 0 0
And, when plotting i just got a flat line. See image below:
plot.ts(Pedidos_meses_1314)
Step2: However, changing frequency, in the ts() function, to 365 (for every single day of the year), i got what i was looking for.
Considering that the date column has information on single days, i tried to change the frequency argument to 365. Then i can plot it with "plot.ts".
Pedidos_dias_1314 <- ts(df$Pedidos, frequency = 365, start = c(2013,1), end = c(2014,12))
plot.ts(Pedidos_dias_1314) #i got graph for days from 2013 and 2014.
Upvotes: 2
Views: 7529
Reputation:
You also can use the xts
library:
library(xts)
# Create a fake time serie with growing and decaying phases
set.seed(42)
X.day <- rep(cos(seq(-1,1,length.out = 365)),2) + rnorm(365*2, mean = 0, sd = 0.1)
# Create the sequence of dates
Dates <- seq(as.Date("2013-01-01"), as.Date("2014-12-31"), "day")
# Create the time serie
X.day <- xts(X.day, order.by = Dates)
plot(X.day)
# aggregate the daily data to monthly data using the mean
X.month <- apply.monthly(X.day, mean)
plot(X.month, ylim = range(X.day)) # range(X.day) to keep the same y-axis range as the previous plos
Upvotes: 2
Reputation: 21425
For step 1, you can only zeroes because making the time series will not cause R to add up all the Perdidos values for each month. To do that you can run:
newData<-aggregate(data$Pedidos,list(date=format(as.Date(data$date),"%Y-%m")),sum)
You will then get a data frame with the sum of Perdidos for each month. You can then make a monthly time series and plot it to get what you want.
Pedidos_meses_1314 <- ts(newData$x, frequency = 12, start = c(2013,1), end = c(2014,12))
Upvotes: 0