R Shiny Highcharter - How to use hc_rangeSelector() - r

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

Related

How to add Highchart Bar lines and lables?

i would like to build an interactive chart but i'm very new in highcharts, i want to add average line for the data and change the labels of the bars, now per default say "Series 1:" i want to write "Cdays: ", this is my code now
# Load required R packages
library(highcharter)
# Set highcharter options
options(highcharter.theme = hc_theme_smpl(tooltip = list(valueDecimals = 2)))
df <- data.frame(Year=c('2015','2016','2017','2018','2019'),
CD=c(24, 18, 12, 9, 14))
head(df)
hc <- df %>%
hchart('column',
hcaes(x = Year, y = CD),
color = "#702080", borderColor = "#702080",
pointWidth = 80) %>%
hc_title(text = "Critical Days") %>%
hc_xAxis(categories = 'Critical Days') %>%
hc
Thanks !!
To add the mean line, try using plotLines in hc_yAxis and set the value to mean(df$CD). You can also adjust the color, add a label, etc. here.
To change the "Series 1" you see when hovering over the bars, you should set the name inside of hchart - in this case, "Cdays".
Other minor changes below - including use of df$Year for x-axis text labels.
df %>%
hchart('column',
hcaes(x = Year, y = CD),
color = "#702080",
borderColor = "#702080",
pointWidth = 80,
name = "Cdays") %>%
hc_title(text = "Critical Days") %>%
hc_xAxis(categories = df$Year) %>%
hc_yAxis(
title = list(text = "Cdays"),
plotLines = list(
list(
value = mean(df$CD),
color = "#00FF00",
width = 3,
zIndex = 4,
label = list(
text = "mean",
style = list(color = "#00FF00")
)
)
)
)

Cannot plot hichcharts fro R script in source mode R-Studio

I'm trying to plot some (interactive) highcharts plots for some quantmod works. Plots (in R-studio viewer tab) works fine when I "run" them. or polts then interactively on the console window, but shows nothing when I source the whole program.
How can I source the whole script and get all the plots in the viewer window?
How can I save the plots (from the script) to a pdf file?
thanks.
code example:
library(quantmod)
library(highcharter)
SPY <- getSymbols("SPY", from = Sys.Date() - lubridate::years(3), auto.assign = FALSE)
SPY <- adjustOHLC(SPY)
SPY.EMA.20 <- EMA(Cl(SPY), n = 20)
SPY.EMA.50 <- EMA(Cl(SPY), n = 50)
SPY.RSI.14 <- RSI(Cl(SPY))
SPY.RSI.SellLevel <- xts(rep(70, NROW(SPY)), index(SPY))
SPY.RSI.BuyLevel <- xts(rep(30, NROW(SPY)), index(SPY))
AAPL <- getSymbols("AAPL", from = Sys.Date() - lubridate::years(3), auto.assign = FALSE)
highchart(type = "stock") %>%
hc_add_series(AAPL, name = "AAPL", color = hex_to_rgba("red", 0.7))
hchart(AAPL)
highchart(type = "stock") %>%
hc_yAxis_multiples(
create_yaxis(3, height = c(3, 1, 1), turnopposite = TRUE)
) %>%
hc_add_series(SPY, yAxis = 0, name = "SPY", color = hex_to_rgba("red", 0.7)) %>%
hc_add_series(SPY.EMA.20, yAxis = 0, name = "EMA 20") %>%
hc_add_series(SPY.EMA.50, yAxis = 0, name = "EMA 50") %>%
hc_add_series(SPY$SPY.Volume, yAxis = 1, color = "gray", name = "Volume", type = "column", title = 'volume') %>%
hc_subtitle(yAxis = 1, text = "Volume", align = "left", style = list(color = "#2b908f", fontWeight = "bold")) %>%
hc_add_series(SPY.RSI.14, yAxis = 2, name = "Osciallator", color = hex_to_rgba("green", 0.7)) %>%
hc_add_series(SPY.RSI.SellLevel, yAxis = 2, color = hex_to_rgba("red", 0.7), name = "Sell level") %>%
hc_add_series(SPY.RSI.BuyLevel, yAxis = 2, color = hex_to_rgba("blue", 0.7), name = "Buy level")

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

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.

R Highcharter: tooltip customization

I created a chart using highcharter in a shiny dashboard and I am trying to customize the tooltip. The chart is combined line and scatter plot. I would like it to do the following:
1) Have a single box for hover information (it currently has one for the line and one for scatter)
2) Be able to use different column of information that is not used in the series x or y values
I would like the tooltip to display the following information (whether I hover over the scatter point or line) for each particular x-axis value.
Overall
Mean: 2 [Mean: data$avghours]
Dog: 1 [data$animal: data$hours]
Below is the example code I've written that demonstrates my problem:
library (shiny)
library (shinydashboard)
library (highcharter)
header <- dashboardHeader(title = "Example")
body <- dashboardBody(
fluidRow(
box(title = "example", status = "primary", solidHeader = TRUE,
highchartOutput("chart")
)
)
)
sidebar <- dashboardSidebar()
ui <- dashboardPage(header, sidebar, body)
server <- function(input, output) {
date <- c(1,2,3,4,5,6,7,8,9,10)
hours <- c(1,5,4,1,6,5,7,5,4,3)
avghours <- c(2,2,2,3,3,3,2,2,2,2)
animal <- c("dog","cat","cat","cat","cat","cat","cat","cat","dog","dog")
data <- data.frame(date,hours,avghours,animal)
output$chart <- renderHighchart({
highchart() %>%
hc_add_series(name = "Shipments", data=data$hours, type = "scatter", color = "#2670FF", marker = list(radius = 2), alpha = 0.5) %>%
hc_add_series(name = "Rolling Mean", data=data$avghours, color = "#FF7900") %>%
hc_yAxis(min = 0, title = list(text = "Hours")) %>%
hc_tooltip(crosshairs = TRUE)
})
}
shinyApp(ui, server)
Firt of all, you need to add all the data instead give only the vector (the vector DONĀ“T have all the information to the tooltip you want).
To do this you need change the data argument using the data.frame with the hcaes helper function in the mapping argument to define which variable use in every axis:
highchart() %>%
hc_add_series(data = data, mapping = hcaes(x=date, y=hours), name = "Shipments", type = "scatter", color = "#2670FF", marker = list(radius = 2), alpha = 0.5) %>%
hc_add_series(data = data, hcaes(date, avghours), name = "Rolling Mean", type = "line", color = "#FF7900") %>%
hc_yAxis(min = 0, title = list(text = "Hours")) %>%
hc_tooltip(crosshairs = TRUE)
Then you can use the tooltip argument in every hc_add_series to define the tooltip in each series:
highchart() %>%
hc_add_series(data = data, hcaes(date, hours), name = "Shipments", type = "scatter",
tooltip = list(pointFormat = "tooltip with 2 values {point.animal}: {point.hours}")) %>%
hc_add_series(data = data, hcaes(date, avghours), name = "Rolling Mean", type = "line",
tooltip = list(pointFormat = "Avg hour text! {point.avghours}")) %>%
hc_yAxis(min = 0, title = list(text = "Hours")) %>%
hc_tooltip(crosshairs = TRUE)

Highchart shiny R scatter plot - how to define individual point colors

I'm trying to create a scatter plot in highcharts shiny R but I need to give a different color to points, individually. Consider for instance the following example:
library("MASS")
dscars <- round(mvrnorm(n = 20, mu = c(1, 1), Sigma = matrix(c(1,0,0,1),2)), 2)
highchart() %>%
hc_chart(type = "scatter", zoomType = "xy") %>%
hc_tooltip(
useHTML = TRUE,
pointFormat = paste0("<span style=\"color:{series.color};\">{series.options.icon}</span>",
"{series.name}: <b>[{point.x}, {point.y}]</b><br/>")
) %>%
hc_add_series(data = list.parse2(as.data.frame(dscars)),
marker = list(symbol = fa_icon_mark("car")),
icon = fa_icon("car"), name = "car")
My objective is to give to this 20 points, an unique color.
I tried to set the "fillColor" inside marker list as also as to define the color of the series, both with a vector of 20 colors but I had no success.
Can any one give me a hint?
Thank you
In highcharts (the highcharter) the point can be given as other parameter, same as x and y. So first
library("MASS")
dscars <- round(mvrnorm(n = 20, mu = c(1, 1), Sigma = matrix(c(1,0,0,1),2)), 2)
dscars <- as.data.frame(dscars)
names(dscars) <- c("x", "y") # it's better give a named list IMHO
dscars$color <- colorize(1:nrow(dscars))
colorizeis a function to create a color vector given other vector. In this case the input vector is a sequence (no repeated) so the output will be differents colors. But if you want yo can use your own colors.
highchart() %>%
hc_chart(type = "scatter", zoomType = "xy") %>%
hc_tooltip(
useHTML = TRUE,
pointFormat = paste0("<span style=\"color:{point.color};\">{series.options.icon}</span>",
"{series.name}: <b>[{point.x}, {point.y}]</b><br/>")
) %>%
hc_add_series(data = list_parse(dscars),
marker = list(symbol = fa_icon_mark("car")),
icon = fa_icon("car"), name = "car")
Note we used:
color:{point.color}; in the poinFormat, beacuse every point has its own color in the color accesor.
I used list_parse which parse the data frame in a named list instead of unnamed list so highcharts understand how to use the data. list_parse is the same list.parse3 for old version of highcharts.
Hope it helps.
Is this what you want?
rm(list = ls())
library(highcharter)
library(MASS)
dscars <- data.frame(round(mvrnorm(n = 20, mu = c(1, 1), Sigma = matrix(c(1,0,0,1),2)), 2))
highchart() %>%
hc_chart(type = "scatter", zoomType = "xy") %>%
hc_tooltip(
useHTML = TRUE,
pointFormat = paste0("<span style=\"color:{colorByPoint:true};\">{series.options.icon}</span>",
"{series.name}: <b>[{point.x}, {point.y}]</b><br/>")
) %>%
hc_add_series(data = list.parse2(as.data.frame(dscars)),colorByPoint = TRUE,
marker = list(symbol = fa_icon_mark("car")),
icon = fa_icon("car"), name = "car")

Resources