【问题标题】:dygraph custom labeling on mouseover fails鼠标悬停时的dygraph自定义标签失败
【发布时间】:2016-05-22 21:07:30
【问题描述】:

我正在尝试根据 x 轴上的鼠标悬停点将图表顶部的文本设置为自定义值。我以为我正确地关注了 dygraph 网站上的example。有人可以用我下面的例子来解释如何正确地做到这一点吗?

错误:

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

我的代码:

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

获取日期并以标签形式返回正确字符串的函数(在 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

【问题讨论】:

    标签: r graph dygraphs


    【解决方案1】:

    我希望这对您有所帮助。必须说它需要 R 和 JavaScript 的知识。

    首先,回答您的第一个问题。就语法而言,R 和 JavaScript 之间存在很大差异。

    您提到的代码是 JavaScript 代码。我说的是这个:

    {
        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(???)
                }
            }   
        }   
    }
    

    此代码不能直接在 R 中使用。这就是您收到错误的原因。

    第一个问题的解决方案:

    如果您对dygraphs 包进行一些搜索工作,您会发现一个函数dyAxis 用于操作轴的详细信息。

    其中,您可以直接将与axisLabelFormattervalueFormatter相关的Javascript代码作为字符串传递。

    第二个问题的解决方案:

    关于第二个问题,你可以试试这段代码:

    ## 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];
    }'))
    

    输出:

    【讨论】:

    • 这正是我所需要的,但我在解决第二个问题时遇到了麻烦。是否可以将当前日期传递给将返回正确答案的函数?我可以写函数,只是不知道如何将日期传递给自定义函数?
    • 我用一个简单的函数更新了我的帖子。如果不可能那么好,我只是想确定一下。
    • 您能否通过示例详细说明该函数的作用?
    • 我在我的问题中添加了更多文字。这有帮助吗?
    • 谢谢,我会处理它并在完成后发布。
    猜你喜欢
    • 2021-08-06
    • 2011-09-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2014-05-31
    • 2011-12-01
    • 1970-01-01
    相关资源
    最近更新 更多