Rilcon42
Rilcon42

Reputation: 9763

dygraph custom labeling on mouseover fails

I am trying to set the text at the top of my graph to a custom value, based on the mouseover point on the x axis. I thought I followed the example on the dygraph site correctly. Can someone explain how to do it correctly using my example below?

Error:

Error in dygraph(df, { : object 'axes' not found

My code:

library(quantmod)
data<-getSymbols("USD/EUR",src="oanda",env=NULL)
df<-as.data.frame(data)

df2<-data.frame(row.names(df))
df2$output<-sample(0:10,length(row.names(df)),replace=T)

library(dygraphs)
#dygraph(df)

dygraph(df, {
    axes:{
        x:{
            valueFormatter: function(dte){
                #how to return df2$output with the same date as the date from df that just got passed in? 
                return(???)
            }
        }   
    }   
})

function to take in date and return the correct string as a label (in R):

#pass in date to this function
retString<-function(dateFromDygraph){
 #returns the data
} #I can write this, I just dont know how to use it in the dygraph code you wrote

Upvotes: 3

Views: 743

Answers (1)

Kunal Puri
Kunal Puri

Reputation: 3427

I hope this helps you a bit. Must say it requires knowledge of both R and JavaScript.

First of all, Answering to your first question. There is a big difference between R and JavaScript as far as syntax is concerned.

The Code that you mentioned is a JavaScript Code. I am talking about this:

{
    axes:{
        x:{
            valueFormatter: function(dte){
            #how to return df2$output with the same date as the date from df that just got passed in? 
                return(???)
            }
        }   
    }   
}

This code can not be used directly in R. That's why you are getting the error.

Solution to first Problem:

If you do some searching work on dygraphs package, you will find a function dyAxis which is used to manipulate the axes details.

In that, you can directly pass on the Javascript Code related to axisLabelFormatter and valueFormatter as a character string.

Solution to your second Problem:

As far as second problem is concerned, you may give a try to this code:

## 1:nrow(df) is column binded for a reason. Later, it will be used for finding the Date and the Output to be selected
g <- dygraph(data.frame(1:nrow(df),df$USD.EUR))

## Create the JavaScript Array for Date and Output and access it using the index specified earlier
dyAxis(g,'x',axisLabelFormatter = paste0('function(x){
    var dates = [',paste(paste0("'",df2[['row.names.df.']],"'"),collapse=','),'];

    return dates[x - 1];
}'),valueFormatter = paste0('function(x){
    var out = [',paste(df2$output,collapse=','),'];

    return out[x - 1];
}'))

Output:

enter image description here

Upvotes: 3

Related Questions