I'm plotting a financial time serie on an R-Shiny project using the highcharter package and I want to allow users to add indicators (such as moving averages) on the chart. In order to do that, I conditioned an hc_add_series_xts()
in an if
statement server-side. It works fine, but everytime someone adds an indicator the chart fully reload while I'd prefer a dynamic update. Is there a way to make it?
To better explain my case, It follows a single page Shiny example:
library(shiny)
library(quantmod)
library(highcharter)
library(TTR)
ui <- fluidPage(
mainPanel(
highchartOutput("hc"),
checkboxInput("indicator","Add Moving Average")
)
)
server <- function(input, output) {
output$hc <- renderHighchart({
y <- getSymbols("MSFT", auto.assign=FALSE)
hc <- 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") ))
if(input$indicator){hc <- hc %>% hc_add_series_xts(name = "Moving Average", EMA(Cl(y)))}
return(hc)
})
}
shinyApp(ui = ui, server = server)
PS: I intentionally call all historical prices avaible in order to make perceptible the "full reaload" event.
Currently is not posible update the chart using shiny
beacuse, as you see, chart a new chart.
Have you tried hc_legend(enabled = TRUE)
? So you can show or hide a series clicking over the legend.
hc <- 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") )) %>%
hc_add_series_xts(name = "Moving Average", EMA(Cl(y)), visible = FALSE) %>%
hc_legend(enabled = TRUE)
hc
Hope this help
With your example, jbkunst method is much better than mine. Especially because the rendering of the graph (in ui
) takes much longer than building it (in server
).
However in some cases, the solution of loading your basic object in a variable of the server
function, then add only new indicators when they are selected can improve latency:
server <- function(input, output) {
y <- getSymbols("MSFT", auto.assign=FALSE)
hc <- 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") ))
output$hc <- renderHighchart({
hc_now <- hc
if(input$indicator){hc_now <- hc_now %>% hc_add_series_xts(name = "Moving Average", EMA(Cl(y)))}
return(hc_now)
})
}
The first time it takes a while to load, but changing indicators takes less time
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.