在R amCharts中添加自定义工具提示

时间:2018-03-10 09:37:22

标签: r amcharts

我在R中使用一个名为amCharts的JS库来进行交互式可视化。

在我的情节中,我想在工具提示(即气球)中使用自定义HTML文本。所以尝试使用以下代码:

library(rAmCharts)
Dat = data.frame(x = paste(as.character(-10:10), "%", sep = ""), y = -10:10,
                    z_Balloon = paste("<p style='font-size: 120%; font-weight: bold; margin-bottom: 15px;''></p>
                                          <table>
                                            <tr><th>People Name</th></tr>\
                                            <tr><td>", -10:10, "</td></tr></table>", sep = ""))

###However for '0' there shall not be any Balloon text
Dat[11, 3] = "<NA>"

amPlot(x = Dat$x, y = Dat$y, type = 'line', fill_alphas = .5, balloonText = Dat$z_Balloon)

但是,如您所见,我的代码无法更改工具提示。

如果有人引导我走向正确的方向,我真的很感激。

谢谢,

*****根据Marco的建议更新**

我更新了Marco的代码,以便能够为X = 0显示无气球:

library(rAmCharts)
Dat = data.frame(x = paste(as.character(-10:10), "%", sep = ""), y = -10:10)

balloonFunction <- htmlwidgets::JS(
    "function(item) {",
    "if (item.category != '0%') {",
    "return \'X: \' + item.category + \'<br>Y: \' + item.values.value;",
    "}",
    "else {",
    "return NULL",
    "}",
    "}")

p <- amPlot(x=Dat$x, y=Dat$y, type='line', fill_alphas=0.5) 
p@graphs[[1]]$balloonFunction <- balloonFunction
setBalloon(p, cornerRadius=10, color="white", fillColor="red", textAlign="left")

然而,我仍然无法找到如何合并第三个变量以显示气球的方法。

任何想法都将受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

这是一个可能的解决方案:

library(rAmCharts)
library(purrr)
set.seed(1)
Dat = data.frame(x = paste(as.character(-10:10), "%", sep = ""), y = -10:10, z=rnorm(21))

balloonFunction <- htmlwidgets::JS(
    'function(item) {',
    'if (item.category!="0%") { return \'X: \' + item.category + 
                               \'<br>Y: \' + item.values.value +
                               \'<br>Z: \' + item.dataContext[\'z\'];}',
    '}')

p <- amSerialChart(categoryField = "x", precision = 2) %>%
  setDataProvider(dataProvider = Dat, keepNA = TRUE) %>%
  addGraph(valueField = "y", lineColor = "gray", fillAlphas=0.5, 
           bullet="round", lineThickness=4) %>%
  setChartCursor() %>%
  setBalloon(cornerRadius=10, color="white", fillColor="red", textAlign="left")
p@graphs[[1]]$balloonFunction <- balloonFunction
p@valueAxes <- list(list(title='y-axis name', position='left', axisAlpha=0.5))
p@categoryAxis <- list(title='x-axis name', axisAlpha=0.5)
p

enter image description here