如何在R中的highcharteR中使用base64?

d7v8vwbk  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(126)

假设我们有以下矩阵:

  1. m <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[1:4]))

我们使用highcharteR绘制:

  1. library(highcharter)
  2. hchart(head(m, -1), "bubble", hcaes(),
  3. showInLegend = FALSE)

然后,我们可以用图像替换x轴的标签,例如,对于A:

  1. hchart(head(m, -1), "bubble", hcaes(),
  2. showInLegend = FALSE) %>%
  3. hc_xAxis(type = 'category',
  4. labels = list(
  5. formatter = JS(
  6. "function(){
  7. if(this.value == 'A'){
  8. return '<img src=\"https://www.highcharts.com/samples/graphics/sun.png\"></img>';
  9. } else {
  10. return this.value;
  11. }
  12. }"
  13. ),
  14. useHTML = TRUE
  15. ))

这将给予我们:

但是我们如何使用base64而不是url得到相同的结果呢?有没有什么方法可以把图片嵌入到html的highcharteR文件中?

我尝试将图像转换为base64并将其嵌入到图表中:

  1. image_path <- "https://www.highcharts.com/samples/graphics/sun.png"
  2. image_data <- base64enc::dataURI(file=image_path, mime="image/png")
  3. hchart(head(m, -1), "bubble", hcaes(),
  4. showInLegend = FALSE) %>%
  5. hc_xAxis(type = 'category',
  6. labels = list(
  7. formatter = JS(
  8. sprintf(
  9. "function(){
  10. if(this.value == 'A'){
  11. return '<img src=\"%s\"></img>';
  12. } else {
  13. return this.value;
  14. }
  15. }",
  16. image_data
  17. )
  18. ),
  19. useHTML = TRUE
  20. ))

但这让我没有印象。输出是空白的,html(在输出中)在这个位置只是:<img>

qzlgjiam

qzlgjiam1#

问题是highcharts.js正在验证labels.formatter等函数生成的html。特别是,src属性必须以Highcharts.AST.allowedReferences中包含的值之一开始,请参阅源代码中的内容。
一个简单的解决方案是单独设置src,在当前JavaScript指令序列完成后立即使用setTimeout。这意味着要替换

  1. return '<img src=\"%s\"></img>';

  1. setTimeout(function(){document.getElementById('img_data1').src = '%s'}, 0);
  2. return '<img id=\"img_data1\"></img>';

更规范的解决方案是通过添加"data:"作为允许的前缀来更改Highcharts.AST.allowedReferences。虽然这可以在formatter本身完成:

  1. function(){
  2. if(this.value == 'A'){
  3. if(Highcharts.AST.allowedReferences.indexOf('data:') === -1){
  4. Highcharts.AST.allowedReferences.push('data:')
  5. }
  6. return '<img src=\"%s\"></img>';
  7. } else {
  8. return this.value;
  9. }
  10. }

只对allowedReferences进行一次更改会更有效,例如通过prepending对highcharter生成的htmlwidget的JavaScript语句(或通过特定于您的应用程序的其他初始化钩子):

  1. library(highcharter);
  2. library(htmlwidgets);
  3. library(htmltools);
  4. m <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[1:4]))
  5. image_path <- "https://www.highcharts.com/samples/graphics/sun.png"
  6. image_data <- base64enc::dataURI(file=image_path, mime="image/png")
  7. initCode <- HTML("<script>Highcharts.AST.allowedReferences.push('data:')</script>")
  8. hchart(head(m, -1), "bubble", hcaes(),
  9. showInLegend = FALSE) %>%
  10. prependContent(initCode) %>%
  11. hc_xAxis(type = 'category',
  12. labels = list(
  13. formatter = JS(
  14. sprintf(
  15. "function(){
  16. if(this.value == 'A'){
  17. return '<img src=\"%s\"></img>';
  18. } else {
  19. return this.value;
  20. }
  21. }",
  22. image_data
  23. )
  24. ),
  25. useHTML = TRUE
  26. ))
展开查看全部

相关问题