如何在Chart.js上设置y轴标签?

时间:2019-11-07 17:38:44

标签: javascript asp.net-core chart.js

我正在.net核心项目中使用Chart.js制作条形图,但无法设置Y轴标签。

这是我想要的示例,数量标签向左对齐。

https://drive.google.com/open?id=1AUgNaBU5BGVqzg4GJBtcs2mtDePORPYV

这是我的JS代码。

var chartBar = document.getElementById('barChart').getContext('2d');
var chartBar = document.getElementById('barChart').getContext('2d');
var bar = new Chart(chartBar, {
  type: 'bar',
  data: {
    labels: ['', '', '', '', '', '', '', '', '', '', '', ''],
    datasets: [{
      label: 'Cantidad',
      data: [2, 4, 6, 7, 8, 4, 23, 13, 5, 20, 4],
      backgroundColor: 'rgba(209, 74, 88)',
    }]
  },
  options: {}
});

1 个答案:

答案 0 :(得分:0)

有一种解决方法,您可以用下面显示的代码中的任何值填充ctx。

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    $(function () {
    var chartBar = document.getElementById('barChart').getContext('2d');
    var data = {
            labels: ['', '', '', '', '', '', '', '', '', '', '', ''],
            datasets: [{
                label: 'Cantidad',
                data: [2, 4, 6, 7, 8, 4, 23, 13, 5, 20, 4],
                backgroundColor: 'rgba(209, 74, 88)',
            }]
        };

    var options = {
            maintainAspectRatio: false,
            scales: {
                yAxes: [{
                    ticks: {
                        min: 0,
                        beginAtZero: true,
                    },
                    gridLines: {
                        display: true,
                        color: "rgba(255,99,164,0.2)"
                    },
                    scaleLabel: {
                        display: true,
                        labelString:""
                    }
                }]

        },
        animation: {
            duration: 1,
            onComplete: function () {
                chartBar.fillStyle = "black";
                chartBar.fillText('Quantity', 50, 18);
            }
        }
        };

   var myChart = new  Chart(chartBar, {
            options: options,
            data: data,
            type:'line'

        });
    });
</script>

参考:

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillText

https://www.chartjs.org/docs/latest/configuration/animations.html