Issue Plotting Time Series Line Graph in Plotly - r

I have some code that pulls reservoir elevation from an API. I have sorted the data and plotted it. When I plot it in native R it looks fine and how I would expect:
When I plot it using plotly I get the following:
The y axis appears to be jumbled with some initially low values on top? I'd like to fix this and essentially match what is produced with the plot() function. Any help with this would be much appreciated.
library("rjson")
library('jsonlite')
library('plotly')
CurrentDate = format(Sys.Date(), "%m-%d-%Y")
StartDate = "1850-01-01"
EndDate = CurrentDate
urlWithoutStart =
paste("https://water.usbr.gov/api/web/app.php/api/series?
sites=hdmlc&parameters=Day.Inst.ReservoirElevation.feet,",
"Day.Sum.ReservoirRelease-
Powerplant.af,Day.Avg.ReservoirRelease-
Powerplant.cfs,Day.Inst.ReservoirStorage.af&",
"start=",sep="")
urlWithoutEnd = paste(urlWithoutStart,StartDate,"&end=",sep="")
urlFull = paste(urlWithoutEnd,EndDate,"&format=json",sep="")
LakeMeadAllData = fromJSON(urlFull)
LakeMeadElevation = as.data.frame(LakeMeadAllData[[1]][[18]][[2]][[1]]
[[1]])
LakeMeadElevation$datetime = as.Date(LakeMeadElevation$datetime)
names(LakeMeadElevation) = c("Date","Elevation","Flag")
LakeMeadElevation <- LakeMeadElevation[order(LakeMeadElevation$Date),]
plot_ly(LakeMeadElevation,x=as.Date(LakeMeadElevation$Date),y=
LakeMeadElevation$Elevation,type = 'scatter',mode="line")
plot(LakeMeadElevation$Date,LakeMeadElevation$Elevation,type='l')

setting y to y=as.numeric(LakeMeadElevation$Elevation) solved the problem.

Related

Plotting multiple csv's on one graph in R

I need to plot two sets of data on one graph, and then use locator() to draw a vertical line at a given date. I have the code below and it works until after the plot function. The lines function is not adding the second dataset to my graph.
Can someone please help me understand what I'm doing incorrectly?
Thank you in advance
LMT <- read.csv("LMT.csv",header = T)
JNJ <- read.csv("JNJ.csv",header = T)
LMT$Date <- as.Date(LMT$Date)
JNJ$Date <- as.Date(JNJ$Date)
plot(y=LMT$Adj.Close, x=LMT$Date, ylim = c(0,500), type = "l")
lines(JNJ$Adj.Close,type = "l")

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()

Highlight a period in graph with R

Is there an easy way to highlight the period in R?
Right now I am trying to use the following, but it does not work for me:
library (PerformanceAnalytics)
period <- c("2018-02/2019-01")
chart.TimeSeries(btc_xts,
period.areas = "2018-02/2019-01",
period.color = "lightgrey")
As a result, I see the historical graph, but I do not the the highlighting.
The outcome attached. Who could help?
Thank you!
the result of the action, no highlighting
I've never used the library but reading from the doc of period.areas :
period.areas : these are shaded areas described by start and end dates in a vector of
xts date rangees, e.g., c("1926-10::1927-11","1929-08::1933-03")
The code should be :
library(PerformanceAnalytics)
period = c("2018-02::2019-01")
chart.TimeSeries(btc_xts,
period.areas = period,
period.color = "lightgrey")
`

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"))

How to customize x axis in rCharts r

I have a monthly time series data set from 2013-07 to 2014-07 and I'm trying to plot a bar chart based on that data set in nPlot from rCharts. The plot looks all right however the ticks of x axis only shows 2013-09, 2013-12, 2014-03, 2014-06. So what can I do to change the ticks and show all the month (e.g. 2013-07, 2013-08, 2013-09, ..., 2014-07).
Suppose my rChart plot is called n1. Do I need to change something in n1$xAxis or n1$chart? If so how do I make this modification.
Thanks if there is any suggestions
To accomplish this you will need a little Javascript. I tried to comment in the code what you might want to change. You could also supply an array of values in the tickValues.
library(rCharts)
data(economics, package = 'ggplot2')
p6 <- nPlot(uempmed ~ date, data = economics, type = 'lineChart')
p6$xAxis(
tickFormat = "#!function(d){return d3.time.format('%b %Y')(new Date(d*60*60*24*1000))}!#"
#for everything
#,tickValues = "#!data[0].values.map(function(v){return v[opts.x]})!#"
#for something potentially more sensible
,tickValues = "#!data[0].values
.map(function(v){
return v[opts.x]
})
.filter(function(v){
return d3.time.format('%m')(new Date(v*60*60*24*1000)) == '12' && +d3.time.format('%Y')(new Date(v*60*60*24*1000)) % 10 == 0
})!#"
)
p6

Resources