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

如何用Chart.js创建指定图表?解决点居中及数值显示问题

解决方案

1. X轴分类轴数据点居中

在X轴配置中添加offset: true并设置刻度对齐中心,确保数据点落在分类标签的正中间:

scales: {
  x: {
    offset: true, // 让数据点偏移至分类中心
    ticks: {
      align: 'center' // 刻度文字与分类中心对齐
    }
  },
  y: {
    title: {
      display: true,
      text: 'Price in Euro'
    },
  }
}

2. 数据点上方显示对应数值

借助chartjs-plugin-datalabels插件实现数据点标签展示,步骤如下:

完整修改后的代码

new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Buy', 'Sell'],
    datasets: [
      ...grid.pairs.map(pair => {
        return {
          data: [pair.buyPrice, pair.sellPrice],
          borderColor: '#0d6efd',
          backgroundColor: '#0d6efd',
          pointRadius: [3, 5],
        }
      }),
      {
        label: 'Market Price',
        data: [grid.marketPrice, grid.marketPrice],
        borderColor: 'red',
        backgroundColor: 'red',
      }
    ]
  },
  options: {
    scales: {
      x: {
        offset: true,
        ticks: {
          align: 'center'
        }
      },
      y: {
        title: {
          display: true,
          text: 'Price in Euro'
        },
      }
    },
    plugins: {
      datalabels: {
        anchor: 'top', // 标签定位在数据点上方
        align: 'center', // 水平居中
        color: '#333', // 标签文字颜色
        font: {
          weight: 'bold'
        },
        formatter: (value) => value.toFixed(2) // 格式化数值,保留两位小数
      }
    }
  },
  plugins: [ChartDataLabels] // 注册数据标签插件
})

插件引入说明

  • 若使用CDN,在HTML中添加:
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
    
  • 若使用npm管理依赖,先安装插件:
    npm install chartjs-plugin-datalabels
    
    再在代码中导入注册:
    import ChartDataLabels from 'chartjs-plugin-datalabels';
    Chart.register(ChartDataLabels);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 11:47:22