【问题标题】:How do I set a default chart type and a default scale type in Chart.js?如何在 Chart.js 中设置默认图表类型和默认刻度类型?
【发布时间】:2023-01-12 07:16:24
【问题描述】:

我在一个页面上有一堆图表,它们都是“折线”图表,它们都在 X 轴和 Y 轴上使用“线性”刻度。我很想摆脱不得不做的事情

    const graph1 = new Chart(ctx1, {
        type: 'line',
        options: {
            scales: {
                x: {
                    type: 'linear',
                },
                y: {
                    type: 'linear',
                },
            },
        },
    });

而不是只是做:

    const graph1 = new Chart(ctx1, {});

我尝试设置Chart.defaults.typeChart.defaults.scales.type 无济于事。

还有Chart.options.type

【问题讨论】:

    标签: chart.js


    【解决方案1】:

    如果您想避免重复配置,您可能需要使用默认类型和选项声明和初始化变量,然后使用 ES6 速记语法来表示对象文字。这是一个可能的实现:

    const ctx1 = document.getElementById('myChart1'),
          ctx2 = document.getElementById('myChart2'),
          type = 'line',
          options = {
            scales: {
              x: {
                type: 'linear',
              },
              y: {
                type: 'linear',
              }
            }
          };
    
    function addData(chart, data) {
      chart.data = { datasets: [] };
      chart.data.datasets.push(data);
      chart.update();
    }
    
    let chart1 = new Chart(ctx1, { type, options }); // <--- HERE
    
    addData(chart1, {
      label: 'Dataset 1',
      data: [{ x: 0, y: 10 }, { x: 1, y: 20 }, { x: 2, y: 15 }]
    });
      
    let chart2 = new Chart(ctx2, { type, options }); // <--- HERE
    
    addData(chart2, {
      label: 'Dataset 2',
      data: [{ x: 0, y: 7 }, { x: 1, y: 1 }, { x: 2, y: 3 }]
    });
    .chart-container {
      position: relative;
      height: 40vh;
    }
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <div class="chart-container">
      <canvas id="myChart1"></canvas>
    </div>
    
    <div class="chart-container">
      <canvas id="myChart2"></canvas>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-19
      • 2022-11-03
      相关资源
      最近更新 更多