本文介绍了双轴Chart.js起点不正确(如果为负值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个chart.js图表​​。这是没有负值的情况:

I have a chart.js chart in my app. This is how it looks without negative values:

带有负值:

您可以看到我有双轴Y。如果没有负值,它们将根据需要工作。但是如果有的话,正确的AxisY将从错误的位置开始。
如何使其与左AxisY在同一位置开始?

As you can see I have dual axisY. They work as needed if there are no negative values. But if there are some, right AxisY starts in the incorrect position.How to make it starts in the same place as left AxisY?

这是我的代码:

private  buildOptions(): any {
    return {
        responsive: true,
        title: {
            display: false,
            text: ''
        },
        tooltips: {
            mode: 'index',
            intersect: true
        },
        scales: {
            yAxes: [{
                position: "left",
                id: "y-axis-0",
                fontColor: '#fff'
            }, {
                position: "right",
                id: "y-axis-1",
                fontColor: '#fff'
            }]
        },
        legend: {
            display: true,
            labels: {
                fontColor: '#fff'
            }
        }
    };
}

谢谢。

推荐答案

您是否尝试过为两个轴设置相同的最小值?

Have you tried setting the same min value for both axes?

您可以使用刻度来指定它:

You can use ticks for specifying it:

ticks: {
          min: -5
        }

这是我为您制作的示例片段:

Here's an example snippet I made for you:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, -5, 3, 5, 2, -3],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        position: "left",
        id: "y-axis-0",
        fontColor: '#fff',
        ticks: {
          min: -5
        }
      }, {
        position: "right",
        id: "y-axis-1",
        fontColor: '#fff',
        ticks: {
          min: -5
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.bundle.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:50%;">
  <canvas id="myChart" width="400" height="400"></canvas>
</div>

这篇关于双轴Chart.js起点不正确(如果为负值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:58