R Highcharter:工具提示自定义

时间:2017-10-26 11:42:08

标签: r highcharts r-highcharter

我在闪亮的仪表板中使用highcharter创建了一个图表,我正在尝试自定义工具提示。该图表是组合线和散点图。我希望它能做到以下几点:

1)有一个用于悬停信息的框(它当前有一个用于行,一个用于散布)

2)能够使用系列x或y值中未使用的不同信息列

我希望工具提示显示每个特定x轴值的以下信息(我是否将鼠标悬停在散点或线上)。

总体

平均值:2 [平均值:数据$ avghours]

狗:1 [数据$动物:数据$小时]

下面是我编写的示例代码,用于演示我的问题:

library (shiny)
library (shinydashboard)
library (highcharter)


header <- dashboardHeader(title = "Example")

body <- dashboardBody(

  fluidRow(
    box(title = "example", status = "primary", solidHeader = TRUE, 
        highchartOutput("chart")
    )
   )
)

sidebar <- dashboardSidebar()

ui <- dashboardPage(header, sidebar, body)

server <- function(input, output) {

  date <- c(1,2,3,4,5,6,7,8,9,10)
  hours <- c(1,5,4,1,6,5,7,5,4,3)
  avghours <- c(2,2,2,3,3,3,2,2,2,2)
  animal <- c("dog","cat","cat","cat","cat","cat","cat","cat","dog","dog")
  data <- data.frame(date,hours,avghours,animal)

  output$chart <- renderHighchart({

    highchart() %>%
      hc_add_series(name = "Shipments", data=data$hours, type = "scatter", color = "#2670FF", marker = list(radius = 2), alpha = 0.5) %>%
      hc_add_series(name = "Rolling Mean", data=data$avghours, color = "#FF7900") %>%
      hc_yAxis(min = 0, title = list(text = "Hours")) %>%
      hc_tooltip(crosshairs = TRUE)

  })

}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:4)

首先,您需要添加所有数据而不是仅提供向量(向量DON'T将所有信息都提供给您想要的工具提示)。 要执行此操作,您需要使用datadata.frame参数中使用hcaes辅助函数更改mapping参数,以定义在每个轴中使用哪个变量:

highchart() %>%
  hc_add_series(data = data, mapping = hcaes(x=date, y=hours), name = "Shipments", type = "scatter", color = "#2670FF", marker = list(radius = 2), alpha = 0.5) %>%
  hc_add_series(data = data, hcaes(date, avghours), name = "Rolling Mean", type = "line", color = "#FF7900") %>%
  hc_yAxis(min = 0, title = list(text = "Hours")) %>%
  hc_tooltip(crosshairs = TRUE)

enter image description here

然后,您可以在每个tooltip中使用hc_add_series参数来定义每个系列中的工具提示:

highchart() %>%
  hc_add_series(data = data, hcaes(date, hours), name = "Shipments", type = "scatter",
                tooltip = list(pointFormat = "tooltip with 2 values {point.animal}: {point.hours}")) %>%
  hc_add_series(data = data, hcaes(date, avghours), name = "Rolling Mean", type = "line",
                tooltip = list(pointFormat = "Avg hour text! {point.avghours}")) %>%
  hc_yAxis(min = 0, title = list(text = "Hours")) %>%
  hc_tooltip(crosshairs = TRUE)

enter image description here