library(chartjs4r)

Introduction

Chartjs is initialized in javascript as

new Chart(id, options)

where options contains a list of data and options.

We can create a list of data and options and pass it directly to chartjs.

cjs_list_input_example()
#> $type
#> [1] "bar"
#> 
#> $data
#> $data$labels
#> [1] 1 2 3 4
#> 
#> $data$datasets
#> $data$datasets[[1]]
#> $data$datasets[[1]]$label
#> [1] "dataset 1"
#> 
#> $data$datasets[[1]]$data
#> [1] 1 4 3 2
#> 
#> 
#> 
#> 
#> $options
#> $options$maintainAspectRatio
#> [1] FALSE
#> 
#> $options$resizeDelay
#> [1] 250

Examples

knitr.defaultWidth = '100%' not working?

chunk option: out.width='100%'

x <-
  cjs_list_input_example()

x$data$datasets[[2]] <-
  list(label = 'dataset 2',
       data = c(4,1,3,2))

x %>% 
  chartjs()

chunk option: out.width='100%', out.height='200px'

x$type = 'line'

x %>% 
  chartjs()

chunk option: out.width='100%'

x <- cjs_list_input_example()


x$data$datasets[[1]] <-
  modifyList(x$data$datasets[[1]],
              list(borderColor = rgb(1, 0, 0),
                   backgroundColor = rgb(1, 0, 0, 0.5),
                   borderWidth = 2,
                   borderRadius = 100,
                   borderSkipped = FALSE))

x %>% 
  chartjs()