如何在chartjs中创建堆叠折线图多个Y轴和公共X轴

e37o9pze  于 2023-05-28  发布在  Chart.js
关注(0)|答案(1)|浏览(180)

如何在chartjs中创建堆叠图表,就像在image中一样?但是我希望y2轴的高度比其他y轴的高2倍。我能够创建多个y轴,但不能设置任何规模的高度,我想。

let scales = {
    x: {
      type: "linear",
      position: "left",
      max: res.maxs[0],
    },
    y: {
      type: "linear",
      position: "left",
      stack: "demo",
      stackWeight: 2,
      grid: {
        borderColor: colors.blue,
      },
      max: res.maxs[4],
      min: 0,
      title: {
        display: true,
        text: titlesLabelY[3],
        font: {
          size: 11,
        },
      },
    },
    y2: {
      type: "linear",
      position: "left",
      stack: "demo",
      stackWeight: 2,
      grid: {
        borderColor: colors.blue,
      },
      max: res.maxs[3],
      min: 0,
      title: {
        display: true,
        text: titlesLabelY[2],
        font: {
          size: 11,
        },
      },
      ticks: {
        callback: (value, index, values) => (index == (0)) ? undefined : value.toFixed(1),
      },
    },
  };

先谢谢你了

hgncfbus

hgncfbus1#

这就是stackWeight的作用(参见文档)。同一个堆栈中每个轴的长度与其stackWeight成正比。
因此,如果y2轴的长度应该是yy3的两倍(这两个轴相等),则应该为y2设置stackWeight: 2,为其他两个轴设置stackWeight: 1
下面是一个简单的例子:

const x = Array.from({length: 101}, (_, i)=>({x: i/100}));
const data = {
    datasets: [
        {
            data: x.map(({x})=>({x, y: Math.exp(x+1)})),
            borderColor: 'red',
        },
        {
            data: x.map(({x})=>({x, y: Math.exp(-x+1)})),
            borderColor: 'blue',
            yAxisID: 'y2',
        },
        {
            data: x.map(({x})=>({x, y: Math.sin(x+1)})),
            borderColor: 'green',
            yAxisID: 'y3',
        }
    ]
};
const config = {
    type: 'line',
    data: data,
    options: {
        responsive: true,
        plugins: {
            legend: {
                display: false,
            },
        },

        scales: {
            x: {
                type: 'linear',
            },
            y: {
                stack: 'demo',
                offset: true,
                stackWeight: 1,
            },
            y2: {
                stack: 'demo',
                stackWeight: 2,
                offset: true,
                border: {
                    color: 'black',
                    width: 2
                }
            },
            y3: {
                stack: 'demo',
                offset: true,
                stackWeight: 1
            }
        }
    },
};
new Chart(document.querySelector('#chart1'), config);
<canvas id="chart1" style="height:600px"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.0/chart.umd.js" integrity="sha512-CMF3tQtjOoOJoOKlsS7/2loJlkyctwzSoDK/S40iAB+MqWSaf50uObGQSk5Ny/gfRhRCjNLvoxuCvdnERU4WGg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

相关问题