dreamRs / apexcharter

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

Formatter of axis numbers affects tooltip appearance #14

Closed Alik-V closed 4 years ago

Alik-V commented 4 years ago

Hi Victor,

Hope you had a good weekend.

I am having a problem when trying to round-up the numbers on the ticks on y-axis for better appearance. I use formatter option in ax_yaxis for that, and it seems that this function is affecting the apperance of tooltip numbers as well. Is there a way to keep the tooltip numbers unaffected here? Example here:

df <- data.frame(time = c(2020, 2025, 2030, 2035, 2040),
                 x = c(-10.12, -20.33, -30.44, -40.75, -50.86),
                 y = c(-3.42, -6.73, -10.14, -13.65, -16.96),
                 z = c(-6.82, -13.63, -20.34, -27.15, -33.96))

apexchart(auto_update = FALSE) %>%
  ax_chart(type = "bar") %>%
  ax_plotOptions(bar = bar_opts(horizontal = FALSE,
                                dataLabels = list(
                                  position = "top"
                                ))) %>%
  ax_grid(show = FALSE) %>%
  ax_series(
    list(name = "x",
         data = df$x),
    list(name = "y",
         data = df$y),
    list(name = "z",
         data = df$z)

  ) %>%
  ax_xaxis(
    categories = df$time,
    axisBorder = list(color = "black"),
    axisTicks = list(show = TRUE)
  ) %>%
  ax_yaxis(
    show = TRUE,
    axisTicks = list(show = TRUE,
                     color = "black"),
    axisBorder = list(show = TRUE,
                      color = "black"),
    labels = list(minWidth = 60,
                  formatter = JS(
                    "function (val){
                     return val.toFixed(0)
                     }"
                  )
    ),
    title = list(
      text = "Prevalence (Mn)",
      style = list(fontSize = "14px",
                   fontWeight = "normal")
    )
  )

Thanks! Best wishes, Alik

pvictor commented 4 years ago

Hello Alik,

Good week-end at home with the lockdown :p

Yes, using a formatter for y-axis will alter the tooltip, I don't think there's an option to prevent it, but you can use a formatter for tooltip (and for dataLabels too), small example :

apexchart() %>% 
  # ...
  ax_yaxis(
    labels = list(
      minWidth = 60,
      formatter = format_num(".0f")  # no decimals
    )
  ) %>% 
  ax_tooltip(
    y = list(                        # y value in the tooltip
      formatter = format_num(".2f")  # 2 decimals
    )
  ) %>% 
  ax_dataLabels(                    # Value displayed on bars
    formatter = format_num(".0f")   # no decimals
  )

I used format_num here, that under the hood call d3.format, but your JavaScript function will work the same.

Best,

Victor

Alik-V commented 4 years ago

Hi Victor,

That worked great, thank you :)

Best wishes, Alik