如何在Chart.js中将Y轴值从数字更改为字符串?

时间:2016-08-26 13:07:05

标签: javascript chart.js

我正在使用Chart.js并尝试更改y轴(请参阅下面的屏幕截图)。我尝试使用字符串数组填充yLabels属性。但那并没有奏效。任何帮助将不胜感激!

my bar chart

 jQuery(document).ready(function($) {
    'use strict ';
    var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ["HTML", "CSS", "SCSS", "JavaScript"],
            yLabels: [
                'newb',
                'codecademy',
                'code-school',
                'bootcamp',
                'junior-dev',
                'mid-level',
                'senior-dev',
                'full-stack-dev',
                'famous-speaker',
                'unicorn'
            ],
            datasets: [{
                data: [12, 19, 3, 10],
                backgroundColor: [
                    'rgba(255, 159, 64, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(255, 206, 86, 0.2)'

                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)'

                ],
                borderWidth: 1
            }]
        },
        options: {
            legend: {
                display: false
            },
            // scales: {
            //     yAxes: [{
            //         ticks: {
            //             beginAtZero: true
            //         }
            //     }]
            // },
            title: {
                display: true,
                text: 'Shameless Bar Graph to show proficency in skills'
            }
        }
    });
});

1 个答案:

答案 0 :(得分:4)

yAxes标签实际上存储在图表的options中,而不是您data

如果您查看the docs稍微向上滚动),您会看到必须编辑刻度线的callback属性在options.scales.yAxes

<小时/> 为了做你想做的事,我在你的代码中添加了一个JS对象:

// Replace the value with what you actually want for a specific key
var yLabels = {
    0 : 'newb', 2 : 'codecademy', 4 : 'code-school', 6 : 'bootcamp', 8 : 'junior-dev',
    10 : 'mid-level', 12 : 'senior-dev', 14 : 'full-stack-dev', 16 : 'famous-speaker',
    18 : 'unicorn', 20 : 'harambe'
}

然后在callback

options: {
    scales: {
        yAxes: [{
            ticks: {
                callback: function(value, index, values) {
                    // for a value (tick) equals to 8
                    return yLabels[value];
                    // 'junior-dev' will be returned instead and displayed on your chart
                }
            }
        }]
    }
}

查看结果this jsFiddle