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

使用Chart.js在同一页面创建两个饼图,其中一个无法显示

解决Chart.js同一页面两个饼图其中一个不显示的问题

问题根源

第一个饼图无法渲染图形的核心错误是配置对象的数据源属性名不符合Chart.js规范:你在config1中写了data1,但Chart.js要求配置对象必须通过data属性指定数据源,框架找不到正确的数据源,因此仅能显示标题,无法生成饼图。

另外,代码中使用了plugins.labels配置,这依赖chartjs-plugin-labels插件,如果没有引入该插件,也可能引发报错影响渲染,可根据需求选择保留(需引入插件)或删除该配置。

修正后的完整代码

<div>
  <div style="width: 300px;">
    <canvas id="piechart1"></canvas>
  </div>
</div>
<script>
  // setup 
  const data1 = {
    labels: ['connect', 'disconnect'],
    datasets: [{
      label: 'Weekly Sales',
      data: [40,60],
      backgroundColor: [
        'rgba(255, 26, 104, 0.2)',
        'rgba(54, 162, 235, 0.2)'
      ],
      borderColor: [
        'rgba(255, 26, 104, 1)',
        'rgba(54, 162, 235, 1)'
      ],
      borderWidth: 1
    }]
  };

  // config 修正data属性名
  const config1 = {
    type: 'pie',
    data: data1, // 这里把data1改成data: data1
    options: {
      plugins:{
          // 若未引入chartjs-plugin-labels,建议删除labels配置
          // labels:{
          //     render: 'percentage',
          //     // position:'outside'
          // },
          title: {
                display: true,
                text: 'Electromechanical',
                padding: {
                    top: 10,
                },
                font: {
                size: 18
            }
            }
      }
    },
  };

  // render init block
  const piechart1 = new Chart(
    document.getElementById('piechart1'),
    config1
  );
</script>

<div>
  <div style="width: 300px;">
    <canvas id="myChart"></canvas>
  </div>
</div>
<script>
  // setup 
  const data = {
    labels: ['connect', 'disconnect'],
    datasets: [{
      label: 'Weekly Sales',
      data: [98,2],
      backgroundColor: [
        'rgba(255, 26, 104, 0.2)',
        'rgba(54, 162, 235, 0.2)'
      ],
      borderColor: [
        'rgba(255, 26, 104, 1)',
        'rgba(54, 162, 235, 1)'
      ],
      borderWidth: 1
    }]
  };

  // config 
  const config = {
    type: 'pie',
    data,
    options: {
      plugins:{
          // 同样,未引入插件则删除labels配置
          // labels:{
          //     render: 'percentage',
          //     // position:'outside'
          // },
          title: {
                display: true,
                text: 'Traffic',
                padding: {
                    top: 10,
                },
                font: {
                size: 18
            }
            }
      }
    },
  };

  // render init block
  const myChart = new Chart(
    document.getElementById('myChart'),
    config
  );
</script>

关键修正点

  • 将config1中的data1改为data: data1,确保Chart.js能正确识别数据源。
  • 若未引入chartjs-plugin-labels插件,删除plugins.labels配置,避免不必要的报错。

内容的提问来源于stack exchange,提问作者蘇友晟

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:35:27