dreamRs / apexcharter

:bar_chart: R Htmlwidget for ApexCharts.js
https://dreamrs.github.io/apexcharter
Other
138 stars 15 forks source link

Adding Icons or Color to the Tooltip #50

Closed systats closed 3 years ago

systats commented 3 years ago

Hi Victor,

just a small question. I really like the tooltips for many series and just want to adapt the value by either coloring red or green depending on the value being over 0 or add an up or down html icon to the tooltip. Where could i start? Because building the tooltip from scratch is quite a bit.

mtcars %>% 
  dplyr::select(mpg, qsec) %>% 
  dplyr::add_rownames("car") %>% 
  dplyr::mutate(diff_mpg = round(mpg - lag(mpg), 1), diff_qsec = round(qsec - lag(qsec), 1)) %>%
  dplyr::select(car, diff_mpg, diff_qsec) %>% 
  tidyr::gather(var, value, -car) %>% 
  apexcharter::apex(type = "bar", apexcharter::aes(car, value, fill = var)) %>% 
  apexcharter::ax_plotOptions(bar = apexcharter::bar_opts(
    horizontal = FALSE,
    endingShape = "flat",
    columnWidth = "70%",
    dataLabels = list(
      position = "top"
    ))
  ) %>% 
  list()

Thanks in Advance!

pvictor commented 3 years ago

Hello Simon,

You have to use some JavaScript in tooltip's formatter, here's an example:

library(dplyr)
library(tidyr)
library(apexcharter)

my_data <- mtcars %>% 
  select(mpg, qsec) %>% 
  add_rownames("car") %>% 
  mutate(diff_mpg = round(mpg - lag(mpg), 1), diff_qsec = round(qsec - lag(qsec), 1)) %>%
  select(car, diff_mpg, diff_qsec) %>% 
  gather(var, value, -car)

my_chart <- apex(my_data, type = "bar", aes(car, value, fill = var)) %>% 
  ax_plotOptions(bar = bar_opts(
    horizontal = FALSE,
    endingShape = "flat",
    columnWidth = "70%",
    dataLabels = list(
      position = "top"
    ))
  ) 

# Color value
my_chart %>% 
  ax_tooltip(
    y = list(
      formatter = JS(
        "function(value) {",
        "var color = value >= 0 ? 'forestgreen' : 'firebrick';",
        "return '<span style=\"font-weight: 700; color:' + color + ';\">' +  value + '</span>';",
        "}"
      )
    )
  )

# Use an icon: first we need to add FontAwesome dependency
my_chart$dependencies <- htmltools::htmlDependencies(shiny::icon("home")) # add FontAwesome HTML dependency
my_chart %>% 
  ax_tooltip(
    y = list(
      formatter = JS(
        "function(value) {",

        # https://fontawesome.com/v4.7.0/icon/arrow-down
        "var icon_up = '<i class=\"fa fa-arrow-up\" aria-hidden=\"true\"></i>';",
        "var icon_down = '<i class=\"fa fa-arrow-down\" aria-hidden=\"true\"></i>';",

        "var icon = value >= 0 ? icon_up : icon_down;",
        "return value + '  ' + icon;",
        "}"
      )
    )
  )

With colors it gives: image

And with icon: image

Of course you can combine the two or color the icon.

Victor

systats commented 3 years ago

thanks a lot. Works perfect.