---
title: "Linked tooltip"
output: 
  rmarkdown::html_vignette:
    lib_dir: "billboarder"
vignette: >
  %\VignetteIndexEntry{Linked tooltip}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup}
library(billboarder)
data("economics", package = "ggplot2")
```

With {billboarder} you can link tooltip between charts, i.e. when you hover over a graph, the tooltip will be displayed on all graphs linked with the same id.

Here a function to draw a line chart, the important part is `bb_tooltip(linked = list(name = "my-tooltip"))` at the end, it's where we declare an ID to link charts. All charts with the name `"my-tooltip"` will be linked.

```{r}
draw_line <- function(var, title, percent = TRUE) {
  billboarder(height = "250px") %>%
    bb_linechart(data = economics[, c("date", var)]) %>% 
    bb_x_axis(tick = list(format = "%Y-%m", fit = FALSE)) %>%
    bb_y_axis(
      min = min(pretty(economics[[var]])), 
      max = max(pretty(economics[[var]])),
      padding = list(bottom = 0),
      tick = list(values = pretty(economics[[var]]), format = if (percent) suffix("%"))
    ) %>% 
    bb_legend(show = FALSE) %>% 
    bb_y_grid(show = TRUE) %>% 
    bb_labs(title = title) %>% 
    bb_tooltip(linked = list(name = "my-tooltip")) # <--- Id for linking tooltip
}
```


We can draw several line charts that will be linked to each other :

```{r, eval=FALSE}
draw_line("psavert", "Personal savings rate", TRUE)
draw_line("uempmed", "Number of unemployed", TRUE)
draw_line("pce", "Personal consumption expenditures", FALSE)
draw_line("pop", "Total population", FALSE)
```


```{r, echo=FALSE}
draw_line("psavert", "Personal savings rate", TRUE)
```

```{r, echo=FALSE}
draw_line("uempmed", "Number of unemployed", TRUE)
```

```{r, echo=FALSE}
draw_line("pce", "Personal consumption expenditures", FALSE)
```

```{r, echo=FALSE}
draw_line("pop", "Total population", FALSE)
```


It also works in Shiny applications : 

```{r, eval = FALSE}
library(shiny)

ui <- fluidPage(
  fluidRow(
    column(
      width = 10, offset = 1,
      tags$h2("Linked tooltip in {billboarder}"),
      fluidRow(
        column(width = 6, billboarderOutput("g1")),
        column(width = 6, billboarderOutput("g2")),
        column(width = 6, billboarderOutput("g3")),
        column(width = 6, billboarderOutput("g4"))
      )
    )
  )
)

server <- function(input, output, session) {
  output$g1 <- renderBillboarder(
    draw_line("psavert", "Personal savings rate", TRUE)
  )
  output$g2 <- renderBillboarder(
    draw_line("uempmed", "Number of unemployed", TRUE)
  )
  output$g3 <- renderBillboarder(
    draw_line("pce", "Personal consumption expenditures", FALSE)
  )
  output$g4 <- renderBillboarder(
    draw_line("pop", "Total population", FALSE)
  )
}

shinyApp(ui, server)
```



