热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

动态更改ChartJs轴标题

如何解决《动态更改ChartJs轴标题》经验,为你挑选了1个好方法。

我已经创建了这样的图表

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,
        }
    }
});

这是图表的默认配置,数据是动态添加的,但用户可以选择显示不同的数据值,如温度,距离......为此,我只需更改数据集和标签的数据值,但是当我更改数据集值时,我无法想象如何使用Javascript更改yAxis标签.初始化标题没问题.

有小费吗?

谢谢!



1> jordanwillis..:

您可以通过更新labelString图表对象options属性中的值并调用.update()原型方法来更改比例标题.

假设我有一个图表实例调用myBar(实例是从Chart.js构造函数返回的),那么我可以使用下面的例子来更改y轴标题.

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

这是一个代码集,演示了一个这方面的工作示例.只需点击"更改标题"按钮即可查看是否有效.


推荐阅读
author-avatar
岩蕃wy之人
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有