简体   繁体   中英

Change ChartJs axis title dynamically

I've created a chart like this

if (userLanguageCode === "es") {
    customTooltipFormat = 'DD/MM/YYYY, HH:mm:ss';

    customDisplayFormats = {
        'millisecond': 'SSS [ms]',
        'second': 'HH:mm:ss', // 11:20:01 AM
        'minute': 'D/MM/YY HH:mm', // 11:20:01 AM
        'hour': 'D/MM/YY HH[h]', // Sept 4, 5PM
        'day': 'D/MM/YYYY', // Sep 4 2015
        'week': 'll', // Week 46, or maybe "[W]WW - YYYY" ?
        'month': 'MMM YYYY', // Sept 2015
        'quarter': '[Q]Q - YYYY', // Q3
        'year': 'YYYY', // 2015
    };
}

Chart.defaults.global.responsive = true;
Chart.defaults.global.animation = false;

datosChartHistoricos =  {
    labels: [],
    datasets: [{
        label: textoValor,
        backgroundColor: "rgba(0,181,255,0.5)",
        fill: chartWithIncrementValues? true: false,
        borderColor: "rgba(0,192,192,1)",
        pointBorderColor: "rgba(0,181,255,1)",
        pointBackgroundColor: "rgba(255,255,255,1)",
        pointBorderWidth: 1,
        data: []
    }]
};

var ctx = document.getElementById("grafica").getContext("2d");
chartHistoricos = new Chart(ctx, {
    type: chartWithIncrementValues? "bar" : "line",
    data: datosChartHistoricos,
    options: {
        responsive: true,
        elements: {
            rectangle: {
                borderWidth: 1,
                borderColor: 'rgb(0, 0, 0)',
                borderSkipped: 'bottom'
            }
        },
        scales: {
            xAxes: [{
                type: "time",
                time: {
                    tooltipFormat: customTooltipFormat,
                    displayFormats: customDisplayFormats,
                }
            }, ],
            yAxes: [{
                scaleLabel: {
                    display: true,
                    labelString: textoValor + " (" + unidadesValor + ")"
                }
            }]
        },
        legend: {
            display: false,
        }
    }
});

This is the default config for the chart, data is added dynamically, but the user can choose different data values to show, like temperature, distance... To do this, I just change the data value of the dataset and the label, but I can't figure how to change the yAxis label using javascript when I change the dataset value. Initialization title is ok.

Any tips?

Thanks!

You can change the scale title simply by updating the labelString value in your chart object's options property and calling the .update() prototype method.

Assuming I have a chart instance called myBar (the instance is what is returned from the Chart.js constructor), then I can use the below example to change the y-axes title.

myBar.options.scales.yAxes[0].scaleLabel.labelString = "My New Title";
myBar.update();

Here is a codepen that demonstrates a working example of this. Just click on the "Change Title" button to see if work.

in V3 the scales have changed so every scale is its own object, to get jordanwillis answer to work you will need to change it to:

myBar.options.scales.y.title.text = 'New title';
myBar.update();

But you can also use scriptable options which update automatically when the chart gets redrawn so you can do it internally in the options object itself:

 var options = { type: 'line', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], borderColor: 'pink' }, { label: '# of Points', data: [7, 11, 5, 8, 3, 7], borderColor: 'orange' }, { label: '# of People', data: [3, 1, 9, 3, 7, 4], borderColor: 'lightBlue' } ] }, options: { scales: { y: { title: { display: true, text: (ctx) => { const chart = ctx.scale.chart; const chartStatus = chart.data.datasets.map((e, i) => (!!chart.getDatasetMeta(i).hidden)); if (chartStatus.every(e => e === false)) { return 'no datasets hidden' } else if (chartStatus.every(e => e === true)) { return 'all datasets hidden' } else { let ret = chartStatus.reduce((acc, curr, i) => { if (curr) { acc += ` ${i},` } return acc; }, chartStatus.indexOf(true) === chartStatus.lastIndexOf(true) ? 'dataset:' : 'datasets:') ret = ret.substring(0, ret.length - 1) ret += ' hidden' return ret } } } } } } } var ctx = document.getElementById('chartJSContainer').getContext('2d'); 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM