simplify_life
simplify_life

Reputation: 405

R programming Highchart Number format

enter image description hereI am trying to draw line chart using Highchart . I need data format in Million format . Ex for the First point in screenshot 2423175 should be shown as 2.42 Million .How do i change format = "{point.y}" to show in Millions

 highchart() %>% 
      hc_add_series(data, hcaes(x = data$Month, y = data$Total, color = data$Total), type = "line",dataLabels = list(
        enabled = TRUE,
        format = "{point.y} "  )
                    ) %>%
      hc_tooltip(cros[![enter image description here][1]][1]shairs = TRUE, borderWidth = 1.5,headerFormat= "",
                 pointFormat = paste("Year: <b>{point.x:%b-%y}</b> <br> Population: <b>{point.y}</b>")) %>%
      hc_title(text = "Population  by year") %>% 
      hc_subtitle(text = "2016-2020") %>%
      hc_xAxis(type = "datetime", title = list(text = "Year")) %>%
      hc_yAxis(title = list(text = "count per year"))      %>%
      hc_legend(enabled = FALSE) %>% 
      hc_add_theme(custom_theme)

Upvotes: 1

Views: 945

Answers (2)

raf18seb
raf18seb

Reputation: 2146

You can use dataLabels.formatter: https://api.highcharts.com/highcharts/series.line.dataLabels.formatter to format your dataLabels. I know how to do it in JavaScript and inject this code inside JS() function in R:

hc_add_series(data, hcaes(x = data$Month, y = data$Total, color = data$Total), type = "line",dataLabels = list(
    enabled = TRUE,
    formatter = JS("function() {
        return (this.y / 1000000).toFixed(2) + 'M'
      }") )
  ) %>%

JS example: https://jsfiddle.net/BlackLabel/o49zcjLv

Let me know if it worked.

Edit: The whole working code with sample data:

library(highcharter)

data <- data.frame(
  y = c(54324232,85325324,10424324,44234324,74324234, 44321413))

highchart() %>% 
  hc_add_series(data, type = "line", hcaes(y = y), dataLabels = list(
    enabled = TRUE,
    formatter = JS("function() {
        return (this.y / 1000000).toFixed(2) + 'M'
      }"
    )))

Upvotes: 1

Saba
Saba

Reputation: 11

Here is a 2 step way of doing it:

First, you need to format your numbers from looking like 2423175 to 2.42 before you create your plot.

data$Total <- format(round(data$Total / 1e6, 1), trim = TRUE)

Next, in order to add 'Million' after your numbers in Highcharter, change format from format = "{point.y} " to format = paste("{point.y} Million") while creating your plot. Your numbers should now be displayed in the format "X.XX Million".

Upvotes: 1

Related Questions