将值添加到rCharts hPlot工具提示

时间:2013-08-06 17:36:11

标签: r highcharts rcharts

我想通过rCharts向标准Highcharts工具提示添加一些额外的值。示例代码:

require(rCharts)
df <- data.frame(x = c(1:5), y = c(5:1), 
             z = c("A", "B", "C", "D", "E"),
             name = c("K", "L", "M", "N", "O"))
h1 <- hPlot(x = "x", y = "y", data = df, type = "scatter", group = "z")

这会生成带有x和y值的工具提示。系列名称为标题。现在我还想将名称值添加到工具提示中。但是我不知道如何做到这一点。

2 个答案:

答案 0 :(得分:3)

rCharts是一个很棒的套餐。但它仍然没有很好的记录(也许我想念这一点)。我认为您需要为tooltip属性重新定义新的JS函数。 任何JS文字需要包装在#!之间!和#!#。这是一个开始,但它不像我想象的那样起作用(我认为是一个好的开始):

h1$tooltip( formatter = "#! function() { return 'x: '     + this.point.x + 
                                                'y: '    + this.point.y  + 
                                                'name: '  + this.point.group; } !#")

答案 1 :(得分:1)

几年后,我有了答案。

似乎像hPlot()这样的包装器函数即使使用简单的自定义格式化程序函数也不支持其他工具提示变量。请参阅下面的工作示例,基于问题的数据集。

require(rCharts)
# create data frame
df <- data.frame(x = c(1:5), y = c(5:1), 
                 z = c("A", "B", "C", "D", "E"),
                 name = c("K", "L", "M", "N", "O"))

# Plot using hPlot() approach
h1 <- hPlot(x = "x", y = "y", data = df, type = "scatter", group = "z")
h1$tooltip(borderWidth=0, followPointer=TRUE, followTouchMove=TRUE, shared = FALSE,
           formatter = "#! function(){return 'X: ' + this.point.x + '<br>Y: ' + this.point.y + '<br>Z: ' + this.point.z + '<br>Name: ' + this.point.name;} !#")
h1

hplot-rcharts

工具提示在上面的示例中不起作用,因为数组中的变量未命名。请参阅str(h1)

# Plot using manual build
h1 <- rCharts:::Highcharts$new()
dlev <- levels(factor(as.character(df$z)))
for(i in 1:length(dlev))
{
  h1$series(data = toJSONArray2(df[df$z==dlev[i],,drop=F], json = F,names=T), name = dlev[i],type = c("scatter"), marker = list(radius = 3))
}
h1$tooltip(borderWidth=0, followPointer=TRUE, followTouchMove=TRUE, shared = FALSE,
           formatter = "#! function(){return 'X: ' + this.point.x + '<br>Y: ' + this.point.y + '<br>Z: ' + this.point.z + '<br>Name: ' + this.point.name;} !#")
h1

manual-build-rcharts

这是有效的,因为数组变量在names=T开始的行中使用h1$series...命名。请参阅str(h1)

这种解决了工具提示问题,但命名数组可能存在其他问题。例如,它会破坏闪亮的应用程序环境中的内容。必须有hPlot()不使用命名数组的原因。