Home > Software design >  Bar plots in dygraphs
Bar plots in dygraphs

Time:05-15

I am trying to replicate the below graph to my dataset (df)

dyBarChart <- function(dygraph) {
  dyPlotter(dygraph = dygraph,
            name = "BarChart",
            path = system.file("plotters/barchart.js",
                               package = "dygraphs"))
}

dygraph(mdeaths) %>%
  dyRangeSelector() %>%
  dyBarChart()

Above it the example where bar plot is applied on mdeaths.

My dataset df is shown below

df1 <- structure(list(Year = c(2021, 2022, 2020, 2021, 2022, 2020, 2021, 
2020, 2021, 2020, 2021, 2020, 2021, 2020, 2021, 2020, 2021, 2020, 
2021, 2020, 2021, 2020, 2021, 2020, 2021), mon_day = c("January", 
"January", "February", "February", "February", "March", "March", 
"April", "April", "May", "May", "June", "June", "July", "July", 
"August", "August", "September", "September", "October", "October", 
"November", "November", "December", "December"), `R` = c(-427, 
-389, 18, -357, -230, -383, -259, -1233, -232, -875, -190, -489, 
-299, -448, -577, -662, -762, -552, -621, -488, -409, -290, -76, 
-155, -10)), row.names = c(NA, -25L), groups = structure(list(
    Year = c(2020, 2021, 2022), .rows = structure(list(c(3L, 
    6L, 8L, 10L, 12L, 14L, 16L, 18L, 20L, 22L, 24L), c(1L, 4L, 
    7L, 9L, 11L, 13L, 15L, 17L, 19L, 21L, 23L, 25L), c(2L, 5L
    )), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", 
    "list"))), row.names = c(NA, -3L), class = c("tbl_df", "tbl", 
"data.frame"), .drop = TRUE), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"))

So I need to plot bar plot for the above datasets using dygraphs. I know we have to convert df to time series but not sure how to convert. Can any one help?

CodePudding user response:

I'm not sure what the purpose of the function is, nor can I tell from your question what this graph is 'supposed to' look like. If this isn't what you're looking for, can you please clarify your question?

I used the libraries dygraphs, xts, and lubridate.

After looking at your data structure, I created a date field. Then I created a time series object. I used R as the value, it seemed like the only one that fit.

# create date and convert to date type
df1$dt = paste0(df1$Year, "-", df1$mon_day, "-", 01) %>% 
  ymd()

str(df1) # validate; looks right

#convert data to xts object
df2 <- xts(x = df1$R, order.by = df1$dt)

# make it pretty
dygraph(df2) %>% dyRangeSelector() %>% dyBarChart()

enter image description here

enter image description here

  •  Tags:  
  • r
  • Related