How to put value on highcharts compare option in R - 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.

Related

Plotly animated map not showing countries with NA values

I posted this in the plotly community forum but got absolutely no activity! Hope you can help here:
I have map time-series data, some countries don’t have data and plotly does not plot them at all. I can have them outlined and they look different but it appears nowhere that the data is missing there (i.e. I want a legend entry). How can I achieve this? Here is a reprex:
library(plotly)
library(dplyr)
data = read.csv('https://github.com/lc5415/COVID19/raw/master/data.csv')
l <- list(color = toRGB("grey"), width = 0.5)
g <- list(
scope = 'world',
countrycolor = toRGB('grey'),
showframe = T,
showcoastlines = TRUE,
projection = list(type = 'natural earth')
)
map.time = data %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code, marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
map.time
Note that the countries with missing data (e.g. Russia) have as many data points as all other countries, the issue is not that they do not appear in the dtaframe passed to plotly.
The obvious way to handle this is to create a separate labels column for the tooltip that reads "No data" for NA values (with the actual value otherwise), then make your actual NA values 0. This will give a uniform appearance to all the countries but correctly tells you when a country has no data.
map.time = data %>%
mutate_if(is.numeric, function(x) {x[is.na(x)] <- -1; x}) %>%
plot_geo() %>%
add_trace(z = ~Confirmed, color = ~Confirmed, frame = ~Date, colors = 'Blues',
text = ~Country, locations = ~Alpha.3.code,
marker = list(line = l)) %>%
colorbar(title = 'Confirmed') %>%
layout(
title = 'Number of confirmed cases over time',
geo = g
) %>%
animation_opts(redraw = F) %>%
animation_slider(
currentvalue = list(
prefix = paste0("Days from ",
format(StartDate, "%B %dnd"),": "))) %>%
plotly_build()
Which gives:

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>';
}

R programming Highchart Number format

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

Setting Order of R Highcharter Categories

I noticed that my bar graphs change in order based on alphabetical order. I'm using a selectinput, thus if a person who is selected with a name beginning in A, they are at the top, but if it is a letter after C, then they move to the bottom. This is not based on the value of the bars, but seems tied to the names. How can I keep the ProviderName at top always?
My hc code is below
hchart(
comparison_prov_df,
type = "bar",
hcaes(x = Metric, y = Value, group = ProviderName),
colorByPoint = F,
showInLegend = T,
dataLabels = list(enabled = T)
) %>%
hc_chart(zoomType = "xy") %>%
hc_tooltip(crosshairs = TRUE, shared = FALSE, borderWidth = 1) %>%
hc_credits(
enabled = TRUE,
text = ""
) %>%
hc_add_theme(hc_theme_elementary()) %>%
hc_legend(enabled = TRUE) %>%
hc_exporting(
enabled = TRUE,
filename = "data"
) %>%
hc_title(
text = "Title",
align = "left"
) %>%
hc_yAxis(
title = list(text = "Y Axis"),
labels = list(
reserveSpace = TRUE,
overflow = "justify"
)
) %>%
hc_xAxis(title = "") %>%
hc_tooltip(pointFormat = "{point.y:.1f}")
I am not sure what the original data is like, but I'll provide a simple example of one way to change the order of items on an axis. You can change the order by simply using hc_xAxis and then listing the category order.
library(highcharter)
library(tidyverse)
df %>%
hchart("bar", hcaes(x = category, y = value, group = group)) %>%
hc_xAxis(
categories = list(
"Pineapples",
"Strawberries",
"Apples",
"Plums",
"Blueberries",
"Oranges"
)
)
Output
Data
set.seed(326)
df <-
data.frame(category = rep(c(
"Apples", "Oranges", "Plums", "Pineapples", "Strawberries", "Blueberries"
), each = 2),
value = round(runif(12, min = 0, max = 100)),
group = rep(c(2020, 2021), 6))

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