chartjs
chartjs copied to clipboard
Render an Image in a chart JS
HI,
I am attempting to plot some charts in chart.js using this package in R for a shiny app. My goal is to plot the chart then add an image using annotation or some other option, based off a URI in my data frame, then ideally add hovertips based on a field in the data frame as well.
This appears to be possible in chart JS using plugins: https://www.chartjs.org/chartjs-plugin-annotation/latest/samples/label/image.html
Is it possible to use plugins in the chartjs R implementation? My attempt so far isn't rendering any images:
data <- data.frame( labels = seq.Date(as.Date("2023-01-01"), as.Date("2023-01-08"), by = 1), values = abs(rnorm(8)) )
Create the chart object
chart <- chartjs(height = "400px") %>% cjsLine(labels = data$labels) %>% cjsEditScale("x", 1, type = "time") %>% cjsEditScale("y", 1, type = "linear") %>% cjsSeries(data = data$values, label = "Sample Data") %>% cjsLegend() %>% cjsOptions( responsive = TRUE, title = list( display = TRUE, text = "Chart with Image Annotation" ), elements = list( line = list( tension = 0.000001 # Adjust the tension value as needed ) ) )
JavaScript for the annotation plugin
js <- " function(el, x, data) { var chart = this.chart;
// Load the annotation plugin var script = document.createElement('script'); script.src = 'https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@latest'; script.onload = function() { chart.options.plugins = chart.options.plugins || {}; chart.options.plugins.annotation = { annotations: { annotation1: { type: 'label', drawTime: 'afterDraw', content: new Image().src = 'https://www.example.com/image.png', // Replace with your image URL width: 100, height: 100, xValue: 'April', yValue: 50, xAdjust: 150, yAdjust: -150, borderWidth: 1, borderDash: [6, 6], callout: { display: true, position: 'left' } }, annotation2: { type: 'point', drawTime: 'afterDraw', xValue: 'April', yValue: 50, radius: 10 } } }; chart.update(); }; document.head.appendChild(script); } "
Add the JavaScript to the chart
chart <- htmlwidgets::onRender(chart, js)
Any help greatly appreciated.