R Highcharter Drilldown Set Ymin & Ymax + Title for each layer - r

I am currently working with the java script wrapper highcharter in R.
I would like to manually set the Y axis for each of the layer, as well as the title for each layer but have not been able to find a way to do so.
E.g the title for all layers are currently "Basic Drilldown", and i would like to update this for each of the drilldowns. As well as I would like to manually set the y axis.
Thanks in advance.
Current code below.
df <- data_frame(
name = c("Animals", "Fruits", "Cars"),
y = c(5, 2, 4),
drilldown = tolower(name)
)
df
hc <- highchart() %>%
hc_chart(type = "column") %>%
hc_title(text = "Basic drilldown") %>%
hc_xAxis(type = "category") %>%
hc_legend(enabled = FALSE) %>%
hc_plotOptions(
series = list(
boderWidth = 0,
dataLabels = list(enabled = TRUE)
)
) %>%
hc_add_series(
data = df,
name = "Things",
colorByPoint = TRUE
)
dfan <- data_frame(
name = c("Cats", "Dogs", "Cows", "Sheep", "Pigs"),
value = c(4, 3, 1, 2, 1)
)
dffru <- data_frame(
name = c("Apple", "Organes"),
value = c(4, 2)
)
dfcar <- data_frame(
name = c("Toyota", "Opel", "Volkswagen"),
value = c(4, 2, 2)
)
hc <- hc %>%
hc_drilldown(
allowPointDrilldown = TRUE,
series = list(
list(
id = "animals",
data = list_parse2(dfan)
),
list(
id = "fruits",
data = list_parse2(dffru)
),
list(
id = "cars",
data = list_parse2(dfcar)
)
)
)
hc
EDIT* updated with answer to dynamically set yaxis for R highcharts.
drilldown = JS('function(e) {
console.log(e.seriesOptions);
this.setTitle({text: e.seriesOptions.name || e.seriesOptions.id });
this.yAxis[0].update({ min: this.yAxis[0].getExtremes().max * 0.5 })}')

First of all, you need to refactor your code a bit, because it's not correct. For example, try to create new variable with all series names and assign this list of names to drilldown field in your data.frame:
names <- c("Animals", "Fruits", "Cars")
df <- data.frame(
name = names,
y = c(5, 2, 4),
drilldown = names
)
Then, change the drilldown id's in your drilldown object definition, because it's not necessary to make them start from lowercase:
hc_drilldown(
allowPointDrilldown = TRUE,
series = list(
list(
id = "Animals",
data = list_parse2(dfan)
),
list(
id = "Fruits",
data = list_parse2(dffru)
),
list(
id = "Cars",
data = list_parse2(dfcar)
)
)
)
The final step is defining the chart.events.drilldown and chart.events.drillup function handlers, inside of which you will set the chart.title.text using Chart.update() function. In order to define it, you have to use JS() R built-in function, just like below:
hc_chart(type = "column", events = list(
load = JS("function() {console.log(this)}"),
drilldown = JS("function(e) {this.update({title: {text: e.seriesOptions.id}})}"),
drillup = JS("function() {this.update({title: {text: 'Basic drilldown' }})}")
)) %>%
Actually, i don't quite understand this part of the question:
As well as I would like to manually set the y axis.
If you describe it more precisely then I will extend the answer.

Related

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

HighCharter HCAES method not producing any visualization in R Shiny Dashboard

Attempting to build off of Stack Exchange Question:
R Highcharter: tooltip customization
Have a R module (below). That ingests some data and provides the UI including highcharter visualizations.
consolidatedlogModuleUI <- function(id){
ns <- NS(id)
tagList(
fluidRow(
bs4Card(highchartOutput(ns("fundedbydayChart")),
width = 12,
collapsible = TRUE)
),
fluidRow(
bs4TabCard(title = "Consolidated Log",
elevation = 2,
width = 12,
bs4TabPanel(
tabName = "tab1",
active = TRUE,
DT::dataTableOutput(ns("consolidatedlogTable"))
),
bs4TabPanel(
tabName = "tab2",
active = FALSE,
DT::dataTableOutput(ns("daysummaryTable"))
)
)
)
)
}
#######
# Consolidated Log Server Module
#######
consolidatedlogModule <- function(input,output,session,data){
ns <- session$ns
data$HasGap <- ifelse(data$GAPGrossRevenue > 0, 1, 0)
data$HasESC <- ifelse(data$ESCGrossRevenue > 0, 1, 0)
consolidatedLogVariables <- c("AcctID", "FSR", "DocSentDate", "DocsToLenderDate",
"FundedDate", "HasGap", "HasESC", "LoanRevenue")
logSummary <- data %>%
group_by(FundedMonthGroup) %>%
summarise(TotalCount = n()
, TotalAmount = sum(LoanRevenue)
, TotalGAP = sum(HasGap)
, TotalESC = sum(HasESC))
daySummary <- data %>%
group_by(FundedDayGroup) %>%
summarise(TotalCount = n()
,TotalAmount = sum(LoanRevenue))
### Consolidated Log Table
output$consolidatedlogTable = DT::renderDataTable({
data[consolidatedLogVariables]
}, extensions = "Responsive", rownames = FALSE,
caption = "Current Consolidated Log",
filter = "bottom"
)
output$daysummaryTable = DT::renderDataTable({
daySummary
}, extensions = "Responsive", rownames = FALSE,
caption = "Current Consolidated Log",
filter = "bottom"
)
### Charts
#Fundedbyday Chart
output$fundedbydayChart = renderHighchart({
highchart() %>%
hc_add_theme(hc_theme_ffx()) %>%
hc_title(text = "Loans Funded By Day") %>%
hc_add_series(data = daySummary, mapping = hcaes(x=FundedDayGroup, y=TotalAmount), type = "column", name = "Daily Loan Revenue",
tooltip = list(pointFormat = "Daily Revenue ${point.TotalAmount} across {point.TotalCount} deals")) %>%
hc_tooltip(crosshairs = TRUE)
# highchart() %>%
# hc_add_theme(hc_theme_ffx()) %>%
# hc_title(text = "Loans Funded By Day") %>%
# hc_add_series(daySummary$TotalAmount, type = "column", name = "Daily Loan Revenue",
# tooltip = list(pointFormat = "Daily Revenue ${point.TotalAmount} across {point.TotalCount} deals")) %>%
# hc_tooltip()
#hchart(daySummary, "column", hcaes(daySummary$FundedDayGroup, daySummary$TotalAmount))
})
}
The highChart function that is commented out works correctly in displaying the columns wanted. The Axis is incorrect and the tooltips is unformatted but the data displays.
Using the Non-commented highchart with the HCAES call and other items, the plot is displayed without any data.
Below is code to reproduce the test data set for the daySummary, the dataframe in question.
FundedDayGroup <- as.Date(c('2019-02-01', '2019-02-4', '2019-02-05'))
TotalCount <- c(1,13,18)
TotalAmount <- c(0, 13166, 15625)
daySummary <- data.frame(FundedDayGroup, TotalCount, TotalAmount)
The issue ended up being Highcharter not interpreting the POSIXct format of the dates and needing to cast the date variable using as.Date. Additionally added some logic to handle the xAxis and setting the datetime. Code below
highchart() %>%
hc_add_theme(hc_theme_ffx()) %>%
hc_title(text = "Loans Funded By Day") %>%
hc_add_series(data = daySummary, mapping = hcaes(x=as.Date(FundedDayGroup), y=TotalAmount), type = "column", name = "Daily Loan Revenue",
tooltip = list(pointFormat = "Daily Revenue ${point.TotalAmount} across {point.TotalCount} deals")) %>%
hc_xAxis(type = "datetime", labels=list(rotation = -45, y = 40) ) %>%
hc_yAxis(title=list(text = "Revenue")) %>%
hc_tooltip(crosshairs = TRUE)

Setting custom value as label in bar highchart (Rshiny)

I have a dataframe with several columns. I draw a bar plot with the values of one of the columns (Ex Count) and I would like to show a label which is not the value of the 'Count' column but the value of the 'Rank' column.
I do not know how to replace the 'point.y' in the dataLabels.
Here is a reproducible example :
library("shiny")
library("highcharter")
data <- data.frame(Name = c("A", "B", "C", "D", "E"),Count=c(38,44,23,29,26), Rank=10:14)
ui <- fluidPage(
fluidRow(
column(width = 8,
highchartOutput("hcontainer",height = "500px")
)
)
)
server <- function(input, output) {
output$hcontainer <- renderHighchart({
chart <- highchart() %>%
hc_chart(type = "bar") %>%
hc_yAxis(title = list(text = "Count"))
chart <- chart %>%
hc_add_series(name="",data = data$Count, dataLabels = list(enabled = TRUE, format='{point.y}'))
return(chart)
})
}
shinyApp(ui = ui, server = server)
Does anyone have an idea ?
Thanks a lot
Sam
Sam,
The easiest way is use hchart function.
hchart(data, "bar", hcaes(x = Name, y = Count),
dataLabels = list(enabled = TRUE, format='{point.Rank}'))
This send all the data to the highchart object so you can extract the info of each point/row (in highcharts /R language) via point.Rank.
The other way is:
highchart() %>%
hc_yAxis(title = list(text = "Count")) %>%
hc_xAxis(categories = data$Name) %>%
hc_add_series(data = data, type = "bar", hcaes(x = Name, y = Count),
dataLabels = list(enabled = TRUE, format='{point.Rank}'))
Here you send all the data again: hc_add_series(data = data, ...) and not only the count values as you did. When you use hc_add_series function with data frames (is a generic function!) you need to use hcaes(x = Name, y = Count) in the mapping argument to specify how to use each variable in the chart.

R Shiny Highcharter - How to use hc_rangeSelector()

I'm plotting a financial intra-day time serie on an R-Shiny project using the highcharter package. I'm using the following code for the server part in order to get the output (note that xtsPrices() is a function that returns an xts intraday time-serie):
output$plot <- renderHighchart({
y <- xtsPrices()
highchart() %>%
hc_exporting(enabled = TRUE)%>%
hc_add_series_ohlc(y) %>%
hc_add_theme(hc_theme_538(colors = c("red", "blue", "green"),
chart = list(backgroundColor = "white") ))
})
I read in the documentation that in order to personalize zoom buttons I have to deal with the hc_rangeSelector() function, but I don't understand how to specify them in this R-Shiny environment as shown for the javascript case in Highstock API. In particular - because it's an intra-day time-serie - I would need buttons like "20min", "1h", "3h", "1D", etc.
For intra-day data you can do something like this:
hc <- highchart() %>%
hc_exporting(enabled = TRUE) %>%
hc_add_series_ohlc(y, yAxis = 0, name = "Sample Data", id = "T1",smoothed=TRUE,forced=TRUE,groupPixelWidth=24) %>%
hc_rangeSelector( buttons = list(
list(type = 'all', text = 'All'),
list(type = 'hour', count = 2, text = '2h'),
list(type = 'hour', count = 1, text = '1h'),
list(type = 'minute', count = 30, text = '30m'),
list(type = 'minute', count = 10, text = '10m'),
list(type = 'minute', count = 5, text = '5m')
)) %>%
hc_add_theme(hc_theme_538(colors = c("red", "blue", "green"),chart = list(backgroundColor = "white") ))
hc

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