How to customize x axis in rCharts r - 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

Related

How to plot multiple y axes with plotly in R for loop

I'm trying to use a for loop to define multiple y axes in plotly graph in R. Below is an example. Does anyone have any suggestions or experience with getting something like this to work?
#example of dataset of plotly to plot multiple y axes in for loop
library(plotly)
len = length(names(mtcars))
names = names(mtcars)
n=0
p= plot_ly()
for (i in names){
n=n+1
p=add_trace(p,data = mtcars, x = mtcars[,"mpg"], y = mtcars[,i], yaxis = paste0('y',ifelse(n==1,'',n)), type = 'scatter', mode = 'scatter')
}
n=0
for (i in 1:len)
{n=n+1
layout(p,assign(paste0('yaxis', ifelse(n==1,"",n)),list( overlaying = "y", side = ifelse((n %% 2) == 0,'right','left'), title = paste0(n, " y axis")
)) )
}
p
I'm thinking that the assign with the multiple paste0's may be causing alot of problems with this. Is there any other way you all can think of to accomplish this? I'm trying to incorporate this into a shiny app to plot functions based on user input. So an lapply() or for loop is ideal. I'm not sure if I'll be able to predefine the yaxes so that all selected variables are plotted. Any help is greatly appreciated. Is there any instance of setting yaxes like this in R? It must be possible right?

Issue Plotting Time Series Line Graph in Plotly

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.

Creating Hexbins with Dates in R hexbin()

I am trying to create hexbins where the x-axis is a date using the hexbin function in the hexbin package in R. When I feed in my data, it seems to convert the dates into a numeric, which gets displayed on the x-axis. I want it force the x-axis to be a date.
#Create Hex Bins
hbin <- hexbin(xData$Date, xData$YAxis, xbins = 80)
#Plot using rBokeh
figure() %>%
ly_hexbin(hbin)
This gives me:
Here's a brute force approach using the underlying grid plotting package. The axes are ugly; maybe someone with better grid skills than I could pretty them up.
# make some data
x = seq.Date(as.Date("2015-01-01"),as.Date("2015-12-31"),by='days')
y = sample(x)
# make the plot and capture the plot
p <- plot(hexbin(x,y),yaxt='n',xaxt='n')
# calculate the ticks
x_ticks_date <-
x_ticks <- axTicks(1, log = FALSE, usr = as.numeric(range(x)),
axp=c(as.numeric(range(x)) ,5))
class(x_ticks_date) <- 'Date'
y_ticks_date <-
y_ticks <- axTicks(1, log = FALSE, usr = as.numeric(range(y)),
axp=c(as.numeric(range(y)) ,5))
class(y_ticks_date) <- 'Date'
# push the ticks to the view port.
pushViewport(p$plot.vp#hexVp.off)
grid.xaxis(at=x_ticks, label = format(y_ticks_date))
grid.yaxis(at=y_ticks, label = format(y_ticks_date))

rchart nvd3 - set tickmark interval

I'd like to specify the interval on the xAxis of a lineChart in rchart nvd3 to be 1.
Currently I have a dynamic chart that has the xAxis being either 0-6, 0-5, or 0-3 - when xAxis only ranges from 0-3, the tickmark interval automatically becomes 0.5, but in this case doesn't make sense, and I would like it to still go by integer intervals - how do I specify that?
Currently my code looks like:
p <- nPlot( yvalue ~ xvalue, data = dat, group = "scenario_id", type = "lineChart" )
p$yAxis(tickFormat = "#!
function(d) {return d3.format('%')(d)}
!#" )
You could try to manually set the tick values by doing:
p$xAxis(tickValues=min(dat$xvalue):max(dat$xvalue))

rcharts nPlot not recognizing quarter values on x-axis

Still very new to using rCharts and R, so please excuse me if the question sounds very stupid!
I'm trying to plot a time series chart using Quarter labels along the x-axis, simple example:
quarters <- c("Q413","Q313","Q213","Q13")
values <- c("120","40","60","80")
testing = data.frame(quarters,values)
tfrPlot <- nPlot(x="quarter", y="values", data = testing, type = "lineChart")
But this doesn't plot the graph and instead generates value between -1 and 1 on the x-axis. I made sure the quarters were factors as well, so I don't know how to proceed.
The error is primarily caused by a typo x="quarter which should be x=quarters, but even with this we will have errors. nvd3 with lineChart expects y to be numeric or continuous, so values<-as.numeric(c("120","40","60","80")) will also be required. Then one last thing the date conversion from R to Javascript in rCharts is still not optimal. One way to force it to work would be to pass the date in numeric form and then tell nvd3 how to handle it. Here is an example:
quarters <- as.Date(c("2013-03-31", "2013-06-30", "2013-09-30", "2013-12-31"))
values <- as.numeric(c("120","40","60","80"))
testing = data.frame(quarters,values)
tfrPlot <- nPlot(x="quarters", y="values", data = testing, type = "lineChart")
tfrPlot$xAxis(
tickFormat =
"#! function(d) {
return d3.time.format('%b %Y')(new Date(d * 24 * 60 * 60 * 1000))
} !#"
)
tfrPlot
You will probably agree this is more painful than it should be, and we are working on a much better way to handle this.

Resources