You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R的chartjs库(Shiny应用)中使用chartjs-plugin-annotation插件

在R chartjs包中实现chartjs-plugin-annotation图片标注

可以实现,R的chartjs包虽未直接封装chartjs-plugin-annotation插件,但通过加载插件脚本+自定义配置的方式,就能实现官网所示的图片标注效果,以下是完整的Shiny应用示例:

library(shiny)
library(chartjs)
library(tidyverse)

ui <- fluidPage(
  # 加载chartjs-plugin-annotation插件脚本
  tags$script(src = "https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@2.2.0/dist/chartjs-plugin-annotation.min.js"),
  chartjsOutput("my_chart")
)

server <- function(input, output) {
  output$my_chart <- renderChartjs({
    set.seed(123) # 固定随机数保证结果可复现
    data <- data.frame( 
      labels = seq.Date(as.Date("2023-01-01"), as.Date("2023-01-08"), by = 1), 
      values = abs(rnorm(8)) 
    )
    
    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)),
        # 添加图片标注的插件配置
        annotation = list(
          annotations = list(
            list(
              type = "label",
              xScaleID = "x",
              yScaleID = "y",
              xValue = as.character(data$labels[4]), # 指定x轴标注位置(第4个日期)
              yValue = max(data$values) * 0.8, # 指定y轴标注位置(最大值的80%处)
              backgroundColor = "transparent", # 透明背景避免遮挡图表
              content = list(
                src = "https://www.example.com/image.png",
                width = 50,
                height = 50
              )
            )
          )
        )
      )
    
    chart
  })
}

shinyApp(ui, server)

关键配置说明

  1. 插件加载:通过tags$script引入chartjs-plugin-annotation的CDN脚本,让Chart.js能识别标注配置项
  2. 标注参数设置:
    • type: "label":指定标注类型为图片标注
    • xScaleID/yScaleID:关联图表的x、y坐标轴,确保标注位置对应图表刻度
    • xValue/yValue:定义图片在图表上的精准坐标位置
    • content:配置图片的路径、宽度和高度,backgroundColor设为透明避免遮挡图表数据

内容的提问来源于stack exchange,提问作者JoeK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 16:52:41