使用HighCharts格式化数据点和Y轴标签

Formatting data points and Y-axis labels using HighCharts

本文关键字:标签 HighCharts 格式化数据 使用      更新时间:2023-09-26

我的数据点由以秒到小数点后两位的时间跨度组成。但是,出于显示目的,我希望这些值以分钟、秒和百分之一为单位进行格式化。例如,值125.78应在工具提示中显示为2:05.78,Y轴标签的格式也应相同。

$(function () {
    $('#container').highcharts({
        title: {
            text: '800 Meter times',
            x: -20 //center
        },
        xAxis: {
            categories: ['3/7', '3/14', '3/21', '3/28']
        },
        yAxis: {
            title: {
                text: 'Times'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle',
            borderWidth: 0
        },
        series: [{
            name: 'Joe Blow',
            data: [125.78, 125.12, 123.88, 124.06]
        }]
    });
});

以下是JSFiddle:http://jsfiddle.net/dhf9nod8/

您可以使用yAxis.labels.formatter来格式化y轴,使用tooltip.formatter来格式化工具提示。并插入以下功能来格式化时间:

var seconds2minutes = function (totalSeconds) {
    //convert to mins and secs
    var min = Math.floor(totalSeconds / 60);
    var remainingSeconds = totalSeconds - 60 * min;
    return min + ":" + (remainingSeconds < 10 ? "0" : "") + remainingSeconds.toFixed(2);
};

然后使用它来格式化y轴

    yAxis: {
        //..your code, then
        labels: {
            formatter:function() {
                return seconds2minutes(this.value);
            }
        }
    },

http://api.highcharts.com/highcharts#yAxis.labels.formatter

然后再次使用它来格式化工具提示。基本要求是

    tooltip: {
        formatter:function () {
            return seconds2minutes(this.y);
    },

然而,这将覆盖默认情况下获得的所有漂亮的HTML,因此为了保持这一点,以下是完整的解决方案:

tooltip: {
    formatter:function () {
        //make the x val "small"
        var retVal="<small>"+this.x+"</small><br />"; 
        //put 2nd line in a div to center vertically
        retVal+="<div style=height:14px;font-size:12px;line-height:14px;>";
        //make the point dot
        var dot="<div style='background-color:"+this.point.color+";height:6px;width:6px;display:inline-block;border-radius:50%;'> </div> ";
        //print the dot, series name, and time in bold
        retVal+=dot+this.series.name+": <strong>"+seconds2minutes(this.y)+"</strong>";
        return retVal;
    },
    useHTML:true //not all styles and tags are enabled by default
},

http://api.highcharts.com/highcharts#tooltip.formatter

还有小提琴:

http://jsfiddle.net/dhf9nod8/2/