Jabberwockey
Jabberwockey

Reputation: 439

How to set R Highcharter stock x-axis dates

I am working with numerically wide data that is grouped by a date, each day just as stock data could be. When using the R Highcharter stock graph, the plot is correctly grabbing the numerical values for the data points/line but the dates are all listed as January 1 1970.

This question was previously posed: R HighCharter Stock Graph not correctly pulling dates but the method for working with the dates and successful uses the hc_add_series_time_values which is now deprecated in the Highcharter package.

Given a data set in R of:

date <- as.Date(c('2020-01-01','2020-01-02','2020-01-03', '2020-01-04', '2020-01-05'))
source <- c(21, 27, 38, 22, 33)
test <- data.frame(date, source)

I would expect the following:

highchart(type = "stock") %>%
hc_add_series(test$source, type = "line")

To produce the stock chart with the dates on the x axis.

I also reviewed Highcharter plotBands, plotLines with time series data thinking that there was a special casting that was needed for the date column but that did not produce the expected result either.

What is the correct process now that the time values function of the highcharter stock component are deprecated to have the x-axis accept the datetime values as datetime values?

Upvotes: 1

Views: 2931

Answers (1)

Ben
Ben

Reputation: 30474

Perhaps you could change your data frame to a time series and still use hc_add_series.

library(tidyverse)
library(highcharter)
library(xts)

test_xts <- xts(test[-1], order.by = date)

highchart(type = "stock") %>%
  hc_add_series(test_xts, type = "line") %>%
  hc_xAxis(labels = list(format = '{value:%b %d}'))

Output

highcarter plot with date on xaxis

Data

date <- as.Date(c('2020-01-01','2020-01-02','2020-01-03', '2020-01-04', '2020-01-05'))
source <- c(21, 27, 38, 22, 33)
test <- data.frame(date, source)

Upvotes: 1

Related Questions