highcharts折线图的简单使用

时间:2021-11-14 05:12:08

第一步:官网下载压缩包https://www.hcharts.cn/download

第二步:HTML中引入highcharts.js

<!DOCTYPE html>
<html><head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="/highcharts/highcharts.js"></script>
</head>
<body>
    <div id="report-view" style="min-width:400px;height:400px"></div>
</body>
</html>

第三步:书写js代码

// 调用,为方便起见,此处没有再封装函数
    $(function(){
        $.post(url,data,function(json){
            if(json.status =="0"){
                viewData(json.result);
            }else{
                alert('请求失败');
            }
        },"json");
    }); 

//初始化折线图
    function viewData(data){
        var chart = new Highcharts.Chart('report-view', {
            credits: {
                enabled: false
            },
            title: {
                text: data.s_time,
                x: -20
            },
            xAxis: {
                categories: data.hour
            },
            yAxis: {
                title: {
                    text: '总计'
                }
            },
            tooltip: {
                valueSuffix: ''
            },
            legend: {
                align: 'center',
                verticalAlign: 'bottom',
                borderWidth: 0
            },
            series: [{
                name: '交易总额(元)',
                color:"#196fec",
                data: stringToNumber(data.amount)
            }, {
                name: '订单数(个)',
                color:"#7c09ef",
                data: stringToNumber(data.order_num)
            }, {
                name: '注册用户(个)',
                color:"#f90d55",
                data: stringToNumber(data.registered_user)
            }]
        });
    }

//将字符串格式化为数字,方便渲染
    function stringToNumber(data) {
        if($.isArray(data)) {
            return data.map(function(item){
                return Number(item);
            })
        }
        if(isString(data)) {
            return Number(data);
        }
    }

其中json的数据格式如下:

{
"status":0,
"msg":"加载成功",
    "result":{
        "s_time":"2017-11-02",
        "hour":[
            "00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00","11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","21:00","22:00","23:00"
        ],
        "amount":[
            "0.00","0.00","0.00","2793.00","3192.00","7589.00","15960.00","22159.00","55972.00","53973.00","10374.00","18672.00","9576.00","9177.00","31122.00","10773.00",
            "41895.00","31521.00","7182.00","11172.00","27930.00","5985.00","35511.00","5187.00"
        ],
        "order_num":[
            0,0,0,"1","1","2","2","2","1","1","1","2","1","1","2","2","2","2","1","2","3","1","2","1"
        ],
        "registered_user":[
            0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
        ]
    }
}

效果图如下:

highcharts折线图的简单使用