---
output: js4shiny::html_document_js
---
```{r htmldeps, echo=FALSE}
library(htmltools)
library(dplyr)
library(tidyr)
library(babynames)
tagList(
div(id = "chart"),
htmltools::htmlDependency(
name = "frappe-charts",
version = "1.3.0",
package = "frappeCharts",
src = "htmlwidgets/lib/frappe-charts",
script = "frappe-charts.min.iife.js",
all_files = TRUE
)
)
```
```{r data}
data <-
babynames %>%
filter(
name %in% c("Ruth", "August"),
year >= 1980
) %>%
group_by(year, name) %>%
summarize(n = sum(n)) %>%
ungroup() %>%
pivot_wider(year, name, values_from = n)
data[1:5, ]
opts <- list(
title = "My AwesomeR Chart",
type = "line",
height = 250,
colors = c("#466683", "#44bc96"),
data = data,
lineOptions = list(regionFill = TRUE, hideDots = FALSE),
axisOptions = list(xIsSeries = TRUE),
isNavigable = c(TRUE, TRUE)
)
tags$script(
id = "chart-opts",
type = "application/json",
htmlwidgets:::toJSON(opts)
)
```
```{js}
let x = document.getElementById('chart-opts')
x = JSON.parse(x.textContent)
const chartData = {labels: [], datasets: []}
// Get keys of data, assume that first entry is for labels, the rest are data
let labelColumn = Object.keys(x.data)[0]
let columns = Object.keys(x.data).slice(1)
// First column in x.data is the labels
chartData.labels = x.data[labelColumn]
// Create an appropriate object for each column, reformat data and add to chartData
columns.forEach(function(col) {
chartData.datasets.push({name: col, values: x.data[col]})
})
x.data = chartData
const chart = new frappe.Chart("#chart", x)
```