Plot Timeseries ts object in R - r

How to plot ts object. month in x axis and monthly.returns in y axis for each year in same graph. please find the code that i am using.
stock<-"^GSPC"
getSymbols(stock,from = "2000-01-01",to = Sys.Date())
GSPC_pr<-monthlyReturn(GSPC)
GSPC_pr<-ts(GSPC_pr,frequency=12, start=c(2000,1))

Presumably you're using the quantmod package. You can plot it like this:
plot(as.xts(GSPC_pr), major.format = "%Y-%m")

Related

Trying to change time labels in R

I'm posting this because i've been having a little problem with my code. What i want to do is to make a forecast of COVID cases in a province for the next 30 days using the AUTOARIMA script. Everything is ok, but when i plot the forecast model, the date labels appears in increments of 25% (IE: 2020.2, 2020.4, etc), but i want to label that axis with a YMD format. This is my code:
library(readxl)
library(ggplot2)
library(forecast)
data <- read_xlsx("C:/Users/XXXX/Documents/Casos ARIMA Ejemplo.xlsx")
provincia_1 <- ts(data$Provincia_1, frequency = 365, start = c(2020,64))
autoarima_provincia1 <- auto.arima(provincia_1)
forecast_provincia1 <- forecast(autoarima_provincia1, h = 30)
plot(forecast_provincia1, main = "Proyeccion Provincia 1", xlab = "Meses", ylab = "Casos Diarios")
When i plot the forecast, this is what appears (with the problem i've stated before on the dates label)
The database is here:
https://github.com/pgonzalezp/Casos-Covid-provincias
Try to create a data.frame having on one column your predictions and in the other the daily dates. Then plot it.
Introduce your start and ending date as seen below, then at "by" argument, please check documentation from this link:
https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/as.Date
df <- data.frame(
date=seq(as.Date("1999-01-01"), as.Date("2014-01-10"), by="6 mon"),
pred_val = forecast_provincia1
)
with(df, plot(date, pred_val ))
I got inspired from here:
R X-axis Date Labels using plot()

Plotting Basic Time Series Data in R - Not Plotting Correctly

I'm trying to plot some time series data. My plot looks like the following:
I'm uncertain as to why it displays the date as such. I'm using R Markdown in R studio. Below is my code:
agemployment<-read.csv("Employment-Level1.csv", header=TRUE)
Tried to change the class of Date:
as.Date(as.character(agemployment$Date),format="%m%d%Y")
That did nothing. Rest of code here:
`attach(agemployment)
View(agemployment)
head(agemployment)
agemployment<-ts(agemployment,frequency=12,start=c(2008, 1))
plot(agemployment, col="black", main="Agriculture Employment Level",
ylab="Total Employment Level (Thousands)", ylim=c(0, 250),lwd=2,
xaxs="i", yaxs="i", lty=1)'
This produces the above plot. I'm uncertain what I'm doing wrong. I would appreciate any help. Thank you!
EDIT:
Data here:
I suspect your issues are somehow driven by attach, generally attaching data frames is not a good practice. The following super-simple code worked for me:
# small dataset from your example, I use package readr to load it as data frame
df = readr::read_csv("DATE,Employment
1/1/2008,1245
2/1/2008,1280
3/1/2008,1343
4/1/2008,1251
5/1/2008,1236
6/1/2008,1265")
ts <- ts(data = df$Employment, frequency = 12, start = c(2008, 1))
plot(ts)
Using the file generated reproducibly in the Note at the end read the file into a zoo object making the index of class "yearmon" (representing year and month without day). Then plot it.
library(zoo)
z <- read.csv.zoo("Employment-Level1.csv", format = "%m/%d/%Y", FUN = as.yearmon)
plot(z)
or
library(ggplot2)
autoplot(z) + scale_x_yearmon()
(continued after plots)
If you wanted to convert z to a ts object or data frame:
tt <- as.ts(z)
DF <- fortify.zoo(z)
Note
Lines <- "DATE,Employment
1/1/2008,1245
2/1/2008,1280
3/1/2008,1343
4/1/2008,1251
5/1/2008,1236
6/1/2008,1265"
cat(Lines, file = "Employment-Level1.csv") # write out file
Realize that by providing an image in the question it means that everyone who answers must retype your data so in the future please provide the input data to questions in a reproducible form as we have done here.

X axis in DateTime format in R script/plot

I am trying to build a forecast plot in R. But, inspite of trying many solutions I am unable to plot my X axis in dates.
My data is in the form of :
Datetime(MM/DD/YYY) ConsumedSpace
01-01-2015 2488
02-01-2015 7484
03-01-2015 4747
Below is the forecast script I am using:
library(forecast)
library(calibrate)
# group searches by date
dataset <- aggregate(ConsumedSpace ~ Date, data = dataset, FUN= sum)
# create a time series based on day of week
ts <- ts(dataset$ConsumedSpace, frequency=6)
# pull out the seasonal, trend, and irregular components from the time series (train the forecast model)
decom <- stl(ts, s.window = "periodic")
#predict the next 7 days of searches
Pred <- forecast(decom)
# plot the forecast model
plot(Pred)
#text(Pred,ts ,labels = dataset$ConsumedSpace)
The output looks like this-- as you can see I have X axis displayed is periods(numbers) rather than in data format.
Any help is highly appreciated.
Try to enter explicit specifications in your plot : plot(x=Date, ...)
if it does not work try :
timeline<-seq(from=your.first.date, to=your.last.date, by="week")
plot(x=...,y=..., xlab=NA, xaxt="n") # no x axis
axis.Date(1, at=(timeline), format=F, labels=TRUE) # Special axis
Edit :
Sorry for my first solution, which does not fit for your timeserie. The problem is there is no date is time series, but an index refering to "start" and "frequency". Here, your problem comes from your use of "frequency", which is supposed to specify the number of observations by unit of time, ie 4 for quarterly data, 12 for monthly data... Here your unit of time is the week, with 6 open days, that's why your graph axes indicates the index ok the weeks. To have a more readable axis you can try this :
dmin<-as.Date("2015-01-01") # Starting date
# Dummy data
ConsumedSpace=rep(c(5488, 7484, 4747, 4900, 4747, 6548, 6548, 7400, 6300, 8484, 5161, 6161),2)
ts<-ts(ConsumedSpace, frequency=6)
decom <- stl(ts, s.window = "periodic")
Pred <- forecast(decom)
plot(Pred, xlab=NA, xaxt="n") # Plot with no axis
ticks<-seq(from=dmin, to= dmin+(length(time(Pred))-1)*7, by = 7) # Ticks sequency : ie weeks label
axis(1, at=time(Pred), labels=ticks) # axis with weeks label at weeks index
You have to use a 7 interval for weeks labels because of the closed day.
It's ugly but it works. There is surely a better way looking closely at your ts() to specify those data are daily data, and adapting your forecasting function.

Display density() graph with date in x axis using R

I have a partial success with
input = "date,data
1-1-2015,5.5
2-1-2016,1.0
3-1-2016,4.0
4-1-2016,4.0
5-1-2019,3.0"
new = read.csv(text=input)
new$date = as.Date(new$date, "%d-%m-%Y")
new$date = as.numeric(new$date, as.Date("2015-01-01"), units="days") #https://stat.ethz.ch/pipermail/r-help/2008-May/162719.html
plot(density(new$date))
Resulting in working graph, unfortunately x axis is obviously formatted as integers. How can I produce graph with x axis formatted as data?
I expected
new = read.csv(text=input)
new$date = as.Date(new$date, "%d-%m-%Y")
plot(density(new$date))
to work, unfortunately it crashed with Error in density.default(new$date) : argument 'x' must be numeric.
density() wasn't really optimized to work with dates. The easiest fix would probably be to just replace the default axis labeling with date values. Here's how you can do that
plot(density(new$date), xaxt="n")
at<-axTicks(1)
axis(1,at, as.Date(at, origin="1970-01-01"))

Plotting Subset Time Interval R

Without using the zoo package, is there a way to use the plot(date,variable) command to restrict the time series for only a specific date range?
Reading through some prior posts, I have a few candidate:
with
which
subset
What is the best way to plot a subset time range of dataset?
Use window():
x = ts(cumsum(rnorm(40)), start = c(2013, 1), freq = 12)
x.sub = window(x, start = c(2014, 1), end = c(2014, 12))
plot(x)
lines(x.sub, col = 'red', lwd = 2)
Or just use xlim to control the x axis display:
plot(x, xlim = c(2014, 2014.5))
You can try xts package. It provides very easy way to subset the timeseries based on time ranges. In example below, X is a xts object. You can subset X by simple text yyyymmdd HH:MM:SS format.
require(xts)
X <- xts(1:100, order.by=Sys.Date()+1:100)
plot(X)
plot(X['201401'])
plot(X['201401/201402'])
plot(X['20140101/20140115'])

Resources