更改 Chartjs 中的 Y 轴单位

Joe*_*Joe 4 chart.js

我觉得这是一个记录不足的功能,但我承认我正在浏览它的可能性要大得多。

我有一个 charjs 对象:

<body>
    <div id="container" style="width: 75%;">
        <canvas id="canvas"></canvas>
    </div>
    <script>
    weekdays=["Monday", "Tuesday", "Wednesday", "Thurday", "Friday", "Saturday", "Sunday", "Monday"]
    var d=new Date()
        var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

        var randomScalingFactor = function() {
            return (Math.random() > 0.5 ? 1.0 : 0) * Math.round(Math.random() * 100);
        };

        var barChartData = {
           labels: [weekdays[d.getDay()], weekdays[d.getDay()-6], weekdays[d.getDay()-5], weekdays[d.getDay()-4], weekdays[d.getDay()-3], weekdays[d.getDay()-2],weekdays[d.getDay()-1]    ],
            datasets: [{
                label: 'Logged Time',
                backgroundColor: "rgba(220,220,220,0.5)",
                data: sessions
            }
            ]

        };

        window.onload = function() {
            var ctx = document.getElementById("canvas").getContext("2d");
            window.myBar = new Chart(ctx, {
                type: 'bar',
                data: barChartData,
                options: {
                    // Elements options apply to all of the options unless overridden in a dataset
                    // In this case, we are setting the border of each bar to be 2px wide and green
                    elements: {
                        rectangle: {
                            borderWidth: 2,
                            borderColor: 'rgb(0, 255, 0)',
                            borderSkipped: 'bottom'
                        }
                    },
                    responsive: true,
                    title: {
                        display: true,
                        text: 'Vision Logged Hours'
                    }
                }
            });

        };




    </script>
Run Code Online (Sandbox Code Playgroud)

看起来像这样:

在此处输入图片说明

我的问题是 y 轴以分钟为单位,而我希望以小时为单位。我对功能集有点迷茫 - 这可能吗?

tek*_*tiv 6

具有简单的手工制作功能:

function minutesToHours(minutes) {
    var hour = Math.floor(minutes / 60);
    minutes = minutes % 60;
    return ((hour < 10) ? "0"+hour : hour) + ":" + ((minutes < 10) ? "0"+minutes : minutes);
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以userCallback像这样使用yAxes 刻度的属性:

options: {
    scales: {
        yAxes: [{
            ticks: {
                userCallback: function(item) {
                    return minutesToHours(item);
                },
            }
        }]
    }
}
Run Code Online (Sandbox Code Playgroud)


你可以在这个小提琴上看到一个工作示例,这是它的结果:

在此处输入图片说明