如何使用chart.js(v2.0-dev)反转y轴

idfiyjo8  于 2023-02-04  发布在  Chart.js
关注(0)|答案(4)|浏览(174)

我正在创建具有2个y轴的折线图。其中一个轴具有两个数据集,但都在0-100的范围内运行。数字越大越好。第二个y轴的范围通常越小(通常为个位数),最佳结果为1。
如何反转第二个y轴,使1位于图表的顶部?
(我会试着自己找到解决方案,但在chart.js中的5 k+行,可能需要一段时间)
谢谢^_^

blpfk2vs

blpfk2vs1#

chart js的Dev 2.0支持在设置轴时反转刻度的选项,这样第二个轴的声明将变为

{
    type: "invertedLinear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
    display: true,
    position: "right",
    id: "y-axis-2",
    ticks: {
        reverse: true
    },
    // grid line settings
    gridLines: {
        drawOnChartArea: false, // only want the grid lines for one axis to show up
    }
}

这是https://jsfiddle.net/nwc8ys34/15/的实际应用

euoag5mw

euoag5mw2#

使用v 2.7.0,以下内容似乎可以正常工作:

options: {
  scales: {
    yAxes: [{
      ticks: {
        reverse: true,
      }
    }]
  }
}
egdjgwm8

egdjgwm83#

在v3中,天平配置已更改,因此可实现所需行为,如下所示:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [40, 80, 100, 70, 60, 80],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange',
        yAxisID: 'y2'
      }
    ]
  },
  options: {
    scales: {
      y: {},
      y2: {
        position: 'right',
        reverse: true
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>
j8yoct9x

j8yoct9x4#

图表js 4:

datasets: [{
    label: "Strength",
    yAxisID: "y1",
    data: mappedData.sigStrength
}, {
    label: "Bars",
    yAxisID: "y2",
    data: mappedData.sigBars
}]
scales: {
    y1: {
        type: "linear",
        display: true,
        position: "left",
        reverse: true
    },
    y2: {
        type: "linear",
        display: true,
        position: "right",
        ticks: {
            stepSize: 1
        }
    }
},

相关问题