R programming Highchart Number format - r

I 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)

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".

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'
}"
)))

Related

Highcharter format number in tooltip

I'm using Highcharts in R, and I want to format the number in the tooltip as a currency without decimal spaces. Right now, numbers appear like this: 34 537 987.21. I want that number to look like this: $34,537,987. Or, better yet, like this: $34M.
Here's a sample of my code:
highchart() %>%
hc_add_series(df,
type = 'spline',
hcaes(x = year, y = data)
) %>%
hc_add_series(df,
type = 'spline',
hcaes(x = year, y = other_data)
) %>%
hc_plotOptions(series = list(marker = list(enabled = TRUE,
hover = TRUE,
symbol = 'circle'))
) %>%
hc_tooltip(
shared = TRUE,
crosshairs = TRUE
)
Use the tooltip parameter inside hc_ad_series() and define as shown below.
highchart() %>%
hc_add_series(df,
type = 'spline',
hcaes(x = year, y = data),
tooltip = list(pointFormat = "$ {point.data}")
) %>%
hc_add_series(df,
type = 'spline',
hcaes(x = year, y = other_data),
tooltip = list(pointFormat = "$ {point.other_data}")
) %>%
hc_plotOptions(series = list(marker = list(enabled = TRUE,
hover = TRUE,
symbol = 'circle'))
)
Hope it helps.

How to put value on highcharts compare option in R

I have this code
serie <- data.frame(date=c("2022-01-01","2022-01-02","2022-01-03"),serie2=c(1,2,5), serie3=c(4,6,7))
serie$date <- as.Date(serie$date)
serie <- tk_xts(serie,data_var = serie$date)
highchart(type = "stock") %>%
hc_title(text = "Comparison") %>%
hc_add_series(serie$serie2,
name = "serie 2",
color = "green", compare = 'percent', compareBase=100) %>%
hc_add_series(serie$serie3, name = "serie 3", color= "white",compare = 'percent', compareBase=100)%>%
hc_add_theme(hc_theme_db())%>%
hc_navigator(enabled = FALSE) %>%
hc_scrollbar(enabled = FALSE) %>%
hc_legend(enabled = TRUE) %>%
hc_exporting(enabled = TRUE) %>%
hc_xAxis(
labels = list(
style = list(
color = "white"
)
)
) %>%
hc_yAxis(
labels = list(format = '{value}%',
style = list(
color = "white"
)
)
)
I need to get this value in R-highcharts. I saw this https://www.highcharts.com/demo/stock/compare but I didnt understand the code because is a little different to R.
Thanks a lot
It's a bit difficult to determine what you are asking for. I think that you're looking to have the tooltips modified, so they match how they are documented in this plot. If so, you can use
hc_tooltip(pointFormat = paste0('<span style="color:{series.color}">{series.name}',
'</span>: <b>{point.y}</b> ({point.change}%)<br/>'),
valueDecimals = 2,
split = T)
Your y-axis is unlabeled, but you have code for formatting it. If you want your y-axis formatted like this plot, you can use
hc_yAxis(formatter = "function(){
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}")
Let me know if there's anything else.

Highcharts in R: sort xAxis in Line Chart

I have a simple line chart, but some categories do not have all periods (xAxis), so the xAxis is not ordered at the end.
That is an example data:
The chart looks like that (with "2019-01" and "2019-03" exchanged)
Example Code
df <- data.frame(PERIODO = c("2017-01","2017-03","2018-01","2018-03",
"2018-03","2019-01",rep("2019-03",2),
"2020-01"),
CATEGORIA = c(rep("A",4),rep("B",2),"A","B","B"),
FRECUENCIA = c(2,3,3,1,2,4,1,1,2))
highchart() %>%
hc_xAxis(type = "category") %>%
hc_add_series(df, "line",
hcaes(x = PERIODO, y = FRECUENCIA,
group = CATEGORIA),
dataLabels = list(enabled = TRUE,
style = list(fontSize = '13px'))
) %>%
hc_legend(enabled = TRUE, align = "right",layout = 'vertical',verticalAlign= "middle") %>%
hc_tooltip(shared = TRUE, crosshairs = TRUE
,style = list(fontSize = "18px")
Someone knows about how to keep the xAxis order by PERIODO: 2017-01,2017-03,2018-01,2018-03,2019-01,2019-03,2020-01
Perhaps you can put your dates PERIODO in Date format (use first day of the month if you only have months).
df$PERIODO <- as.Date(paste0(df$PERIODO, "-01"))
Then, use type = "datetime" instead of category for your hc_xAxis argument. You can indicate what you want as labels on your x-axis using dateTimeLabelFormats.
highchart() %>%
hc_xAxis(type = "datetime",
dateTimeLabelFormats = list(month = '%b %Y')) %>%
...
Default labels and more information can be found here.

Series name with series color at the end of line series

I want series name at the end of line series with color of series. I am looking for similar output present here - Highcharts Line Chart, display series name at the end of line series
I am able to include series name at the end of line series but fails to show it as color of series. This is the solution I am unable to include it in highcharter in R as it has both single and double quotes. R is unable to recognise it.
formatter: function() {
return '<span style="color:'+this.series.color+'">'+this.series.name+'</span>';
}
My Code is shown below -
highchart() %>%
hc_chart(type = "spline") %>%
hc_title(text = "Demo",
align = "center",
style = list(
fontFamily = "Roboto",
color = "#444",
fontWeight = "bold"
)) %>%
hc_xAxis(categories = iris$Species) %>%
hc_yAxis(labels = list(format = "{value}M")) %>%
hc_add_series(name = "Sepal.Length",
data = iris$Sepal.Length,
marker = list(enabled= FALSE),
color='red',
lineWidth=4,
lineColor='red') %>%
hc_add_series(name = "Petal.Length",
data = iris$Petal.Length,
marker = list(enabled= FALSE),
type = "area",
color='#f6f3ef',
lineWidth=3,
lineColor='#e4dcd2',
dashStyle = "ShortDot") %>%
hc_plotOptions(
series = list(
dataLabels = list(
enabled = TRUE,
allowOverlap = TRUE,
align = 'center',
verticalAlign = 'bottom',
style = list(fontSize = '14px', color = '#666'),
formatter = JS("
function() {
if (this.point.x == this.series.data.length - 1) {
return this.series.name;
}
return '';
}")))) %>%
hc_tooltip(pointFormat="{point.series.name}: €<b>{point.y:,.2f}M</b><br/>", shared= TRUE) %>%
hc_add_theme(anacap_theme(palettes = "lightbluegolden")) %>%
hc_exporting(enabled = TRUE)
Can't you escape the double quotes like that since you want to keep double quotes in the markup?
formatter: function() {
return '<span style=\"color:' + this.series.color + '\">' + this.series.name + '</span>';
}

Displaying datatable in highcharter tooltip

Using the first block of code in this post I want to create a tooltip that would display the list of doctors visiting a clinic on a particular day.I tried the following code which displays nothing
library(DT)
tltp = DT:: datatable(data.frame(Doctors = x[x$Clinic=="{point.series}"&x$VisitDate == "{point.x}",2]))
hc%>%hc_tooltip(pointFormat = tltp)
I also tried using the tooltip_table which gives error
tltp = tooltip_table(x = NULL, y = x[x$Clinic=="{point.series}"&x$VisitDate == "{point.x}",2]
hc%>%hc_tooltip(pointFormat = tltp)
Error: unexpected symbol in:
"tltp = tooltip_table(x = NULL, y = x[x$Clinic=="{point.series}"&x$VisitDate == "{point.x}",2]
tltp"
Apologies I am not fluent in writing javascript.
As the official page recommend, to use highcharter is good alternative read how highchartsjs works. So, see this example with a simple custom tooltip.
hc <- hchart(visits, "column", x = as.Date(VisitDate), y = freq, group = Clinic) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = TRUE)
)
Adding the simple tooltip using the column names: Clinic and freq
hc %>%
hc_tooltip(pointFormat = "this is and clinic {point.Clinic} and freq {point.freq}")
The tooltip_table function is to make tables in the tooltip:
tt <- tooltip_table(c("Clinic", "Freq"), c("{point.series.name}", "{point.y}"))
hc %>%
hc_tooltip(pointFormat = tt, useHTML = TRUE)
If you need other data to show in the tooltip you can create the columun:
visits$doctors <- sample(letters, size = nrow(visits))
And then create the chart again (using the new data) and use this column in the tooltip:
hchart(visits, "column", x = as.Date(VisitDate), y = freq, group = Clinic) %>%
hc_plotOptions(column = list(
dataLabels = list(enabled = FALSE),
stacking = "normal",
enableMouseTracking = TRUE)
) %>%
hc_tooltip(pointFormat = "Here is the doctor {point.doctors}")

Resources