I am using highcharter library for a shiny app to make candlesticks chart of an XTS. Code in server.R to generate the chart is given below (sry, this code is not reproducible) By default the chart generated shows data for all period. I want the zoom level to be changed to 1 month. It is equivalent to clicking on "1m" in zoom options. How can I do that?
library(highcharter)
output$ohlcPlot <- renderHighchart({
if (IsValidNSESymbol(input$x1StockCode)) {
df <- loadStockPrices()
highchart(type = "stock") %>%
hc_add_series(data = df,
name = "OHLC",
type = "candlestick") %>%
hc_colors(color = "red")
}
})
You can add %>% hc_rangeSelector(selected = 0) to keep month value as default where 0 is the position of the zoom option.
For eg with AAPL stock.
library(highcharter)
quantmod::getSymbols('AAPL',src = 'yahoo',from = "2013-01-01", to = "2017-12-31")
highchart(type = "stock") %>%
hc_add_series(data = AAPL,
name = "OHLC",
type = "candlestick") %>%
hc_colors(color = "red") %>%
hc_rangeSelector(selected = 0)
Related
I'm producing a set of charts using highcharter. I have items, which each have variants, and units sold by variant. I'm looking for a method by which I can choose which variants are pre-selected to appear on the chart.
Below is an example of the chart I produced:
library(tidyverse)
library(highcharter)
library(viridis)
df <- tibble(item_name = c('beer','beer','soft drink','soft_drink'),
units = c(15,50,25,10),
variant_name = c('blonde','white','coke','lemonade'))
cols = as.vector(scales::viridis_pal(option = "turbo", direction = 1)(length(unique(df$variant_name))))
df %>%
group_by(item_name) %>%
arrange(desc(units)) %>%
ungroup() %>%
hchart(
"column", hcaes(x = item_name, y = units, group = variant_name),
stacking = "normal"
) %>%
hc_colors(c(cols))
I would like to be able to pre-select, let's say 'blonde' and 'coke'. Other variants would have to be selected by clicking on the variant name in the chart:
I haven't been able to find a way to do that so far, the documentation for highcharts only points to doing so when you have multiple series.
You could write your own JS function to load the elements. Where you can specify the chart.series.load, check this link for extra info. Here is a reproducible example:
library(tidyverse)
library(highcharter)
library(viridis)
df <- tibble(item_name = c('beer','beer','soft drink','soft_drink'),
units = c(15,50,25,10),
variant_name = c('blonde','white','coke','lemonade'))
cols = as.vector(scales::viridis_pal(option = "turbo", direction = 1)(length(unique(df$variant_name))))
df %>%
group_by(item_name) %>%
arrange(desc(units)) %>%
ungroup() %>%
hchart(
"column", hcaes(x = item_name, y = units, group = variant_name),
stacking = "normal"
) %>%
hc_chart(events = list(load = JS("function() {
var chart = this;
chart.series[1].setVisible(true)
chart.series[2].setVisible(false)
chart.series[3].setVisible(false)
chart.series[4].setVisible(false)
}"))) %>%
hc_colors(c(cols))
Output:
I am using highcharter library and referred to below link to create an interactive tooltip chart in a bubble chart
https://jkunst.com/blog/posts/2019-02-04-using-tooltips-in-unexpected-ways/
Plot image:
Using gapminder data as shown in link I was able to reproduce the same but when I use my other data then the tool tip chart doesn't appear.
Code for my other data:
libs
library(tidyverse)
library(highcharter)
data
grouped_cases_df <- read.csv("https://raw.githubusercontent.com/johnsnow09/covid19-df_stack-code/main/grouped_cases.csv")
tt_base <- grouped_cases_df %>%
arrange(desc(Date)) %>%
distinct(Country.Region, .keep_all = TRUE)
tt_base
tt_inner <- grouped_cases_df %>%
select(Country.Region, Date, Daily_cases) %>%
nest(-Country.Region) %>%
mutate(
data = map(data, mutate_mapping, hcaes(x = Date, y = Daily_cases), drop = TRUE),
data = map(data, list_parse)
) %>%
rename(tt_nestdata = data)
tt_inner
tt_daily <- left_join(tt_base, tt_inner, by = "Country.Region")
tt_daily
hchart(
tt_daily,
"point",
hcaes(x = Active, y = Confirmed, name = Country.Region,
size = Daily_cases, group = continent, name = Country.Region)
) %>%
hc_yAxis(type = "logarithmic") %>%
hc_tooltip(
useHTML = TRUE,
headerFormat = "<b>{point.key}</b>",
pointFormatter = tooltip_chart(accesor = "tt_nestdata")
) %>%
hc_title(text = "Active Vs Confirmed Cases as of latest Date") %>%
hc_subtitle(text = "Size of bubble based on Deaths <br> (ttchart: population growth)")
Issue: Getting blank tooltip chart for every country.
I also tried by changing Country.Region to as.factor() but didn't help. I am not sure whats wrong with this.
It's needed make two changes:
The tooltip data needs to be ready to highcharter. So you need to transform the Date column from text to date then to a numeric value which highcharts can interpret as date:
mutate(Date = highcharter::datetime_to_timestamp(lubridate::ymd(Date)))
Then, in the hc_opts argument in the tooltip_chart function you need to specify the x Axis treat the values as date.
pointFormatter = tooltip_chart(accesor = "tt_nestdata", hc_opts = list(xAxis = list(type = "datetime")))
Then:
I was using Highchart to plot some time series and wanted to add some annotation to the plot to highlight some key points. I knew putting the cursor on the graph can pop up the context, however, some automatic graph generation is needed and hence annotating is the best approach.
And I did that, with the last line in the code below. However, the effect is not what I expected. The text was located at the bottom left corner, not located at the right horizontal position yet the vertical position is right. The time series are created using xts library, which means the horizontal axis is simply the date data structure, nothing fancy. xValue is specified as the 900th element of all the time points which have a total length of 1018, so the 900th time point must be in the second half of the graph.
Anyone knows how I can put the annotation at the right location? Many thanks.
hc <- highchart(type = "stock") %>%
hc_title(text = "Some time series") %>%
hc_add_series(x, color='green', name="x", showInLegend = TRUE) %>%
hc_add_series(y, color='red', name="y", showInLegend = TRUE) %>%
hc_add_series(z, color='blue', name="z", showInLegend = TRUE) %>%
hc_navigator(enabled=FALSE) %>%
hc_scrollbar(enabled=FALSE) %>%
hc_legend(enabled=TRUE, layout="horizontal") %>%
hc_annotations(list(enabledButtons=FALSE, xValue = index(x)[900], yValue = -5, title =list(text = "Hello world! How can I make this work!")))
hc
The data can be roughly generated using the following script:
dt <- seq(as.Date("2014/1/30"), as.Date("2018/2/6"), "days")
dt <- dt[!weekdays(dt) %in% c("Saturday", "Sunday")]
n <- length(dt)
x <- xts(rnorm(n), order.by=dt)
y <- xts(rnorm(n), order.by=dt)
z <- xts(rnorm(n), order.by=dt)
Let's star with the #kamil-kulig example, this will be a little out of R world but I want to give some justification if you don't mind.
If we see annotations options is not a object but a list of object(s), so in highcharter is implemented the hc_add_annotation function.
Now, you are using a old version of highcharter. Highcharter devlopment version is using v6 of highchartsJS which made some changes: before the annotations.js was a pluging now is included as a module with some changes in the names of arguments.
Example I: Simple
The example by Kamil Kulig is replicated doing:
highchart(type = "stock") %>%
hc_add_annotation(
labelOptions = list(
backgroundColor = 'rgba(255,255,255,0.5)',
verticalAlign = 'top',
y = 15
),
labels = list(
list(
point = list(
xAxis = 0,
yAxis = 0,
x = datetime_to_timestamp(as.Date("2017/01/02")),
y = 1.5
),
text = "Some annotation"
)
)
) %>%
hc_xAxis(
minRange = 1
) %>%
hc_add_series(
pointStart = start,
pointInterval = day,
data = c(3, 4, 1)
)
Example II: With your data
Be careful in the way you add the x position. Highcharter include a datetime_to_timestamp function to convert a date into a epoch/timestap which is required for highcharts.
library(xts)
dt <- seq(as.Date("2014/1/30"), as.Date("2018/2/6"), "days")
dt <- dt[!weekdays(dt) %in% c("Saturday", "Sunday")]
n <- length(dt)
x <- xts(rnorm(n), order.by=dt)
y <- xts(rnorm(n), order.by=dt)
z <- xts(rnorm(n), order.by=dt)
highchart(type = "stock") %>%
hc_title(text = "Some time series") %>%
hc_add_series(x, color='green', name="x", showInLegend = TRUE) %>%
hc_add_series(y, color='red', name="y", showInLegend = TRUE) %>%
hc_add_series(z, color='blue', name="z", showInLegend = TRUE) %>%
hc_navigator(enabled=FALSE) %>%
hc_scrollbar(enabled=FALSE) %>%
hc_legend(enabled=TRUE, layout="horizontal") %>%
hc_add_annotation(
labels = list(
list(
point = list(
xAxis = 0,
yAxis = 0,
x = datetime_to_timestamp(as.Date(index(x)[900])),
y = 1
),
text = "Hello world! How can I make this work!"
)
)
)
Used the below code to make a pie chart in shiny R interface using Highcharts but was unable to name the slices. I have used a dataset stored in csv format from my app folder.
output$Hist<-renderHighchart({
data<-read.csv(paste0(getwd(),"/data.csv"),header=TRUE,stringsAsFactors=FALSE)
highchart() %>%
hc_chart(type = "pie") %>%
hc_plotOptions(
series = list(showInLegend = TRUE)
) %>%
hc_add_series(data = data$Count, name = data$X) %>%
hc_tooltip(valueDecimals = 0,
pointFormat = "Count: {point.y}") %>%
hc_legend(enabled = TRUE)%>%
Image of the chart:
Like this:
library(highcharter)
data <- data.frame(X=c("name1","name2"),Count =c(20,30))
highchart() %>%
hc_add_series_labels_values(data$X, data$Count, name = "Pie",colorByPoint = TRUE, type = "pie")
I am struggling in adding one level drilldown in my grouped column chart made using highcharter. To explain, I am taking using the "vaccines" dataset available in highcharter library :
My code (similar) that creates the grouped column chart :
library (highcharter)
library(dplyr)
df <- na.omit(vaccines[vaccines$year %in% c("1928", "1929"),])
df <- ddply(df, c("state", "year"), summarise, count = sum(count))
hc <- hchart(df, type = "column", hcaes(x = state, y = count, group = year)) %>%
hc_xAxis(title = list(text = "States")) %>%
hc_yAxis(title = list(text = "Vaccines")) %>%
hc_chart(type = "Vaccines", options3d = list(enabled = TRUE, beta = 0, alpha = 0)) %>%
hc_title(text = "Demo Example") %>%
hc_subtitle(text = "Click on the on Year to see the Vaccine drill down")
hc
It creates this grouped chart perfectly
I now want to add one level drill down to the chart where I can select the "Year" and corresponding drill down data of the vaccine selected is presented. Can you please help with the best/easiest way to do it considering I have the individual drill down data also in data frames.
Regards,
Nikhil