javascript - Highchart - 将更多系列添加到多个同步的 Highstock 图表之一

标签 javascript json charts highcharts

我有以下两个相互同步的图表: chart

屏幕截图 enter image description here

数据来自这个JSON

JSON的结构如下:

{
 "xData": [], // the dates go here

 "datasets": [
  {
     "name": "Precipitation",

     "data": [],     // data for precip go here
     "unit": "mm",
     "type": "area",
     "valueDecimals": 3
   },
   {
     "name": "Temperature",

     "data": [],    // data for temp go here
     "unit": "°F",
     "type": "line",
     "valueDecimals": 2
  }
 ]
}

如何向其中一个图表添加其他系列?是否可以在 JSON 文件中执行此操作,而无需修改 javascript?。

这花了我一段时间 - 我真的很想保留当前设置,只是向任一图表添加一个系列(即另一行)。就像这里显示的那样:https://www.highcharts.com/stock/demo/compare

我已经能够修改 JSON 中的大部分内容,然后在 javascript 中指向它。任何帮助将不胜感激。

$(function() {

    /**
     * In order to synchronize tooltips and crosshairs, override the
     * built-in events with handlers defined on the parent element.
     */
    $('#container').bind('mousemove touchmove touchstart', function(e) {
        var chart,
            point,
            i,
            event;

        for (i = 0; i < Highcharts.charts.length; i = i + 1) {
            chart = Highcharts.charts[i];
            event = chart.pointer.normalize(e.originalEvent); // Find coordinates within the chart
            point = chart.series[0].searchPoint(event, true); // Get the hovered point

            if (point) {
                point.highlight(e);
            }
        }
    });
    /**
     * Override the reset function, we don't need to hide the tooltips and crosshairs.
     */
    Highcharts.Pointer.prototype.reset = function() {
        return undefined;
    };

    /**
     * Highlight a point by showing tooltip, setting hover state and draw crosshair
     */
    Highcharts.Point.prototype.highlight = function(event) {
        this.onMouseOver(); // Show the hover marker
        this.series.chart.tooltip.refresh(this); // Show the tooltip
        this.series.chart.xAxis[0].drawCrosshair(event, this); // Show the crosshair
    };

    /**
     * Synchronize zooming through the setExtremes event handler.
     */
    function syncExtremes(e) {
        var thisChart = this.chart;

        if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
            Highcharts.each(Highcharts.charts, function(chart) {
                if (chart !== thisChart) {
                    if (chart.xAxis[0].setExtremes) { // It is null while updating
                        chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, {
                            trigger: 'syncExtremes'
                        });
                    }
                }
            });
        }
    }

    // Get the data. The contents of the data file can be viewed at
    // https://github.com/highcharts/highcharts/blob/master/samples/data/activity.json
    $.getJSON('../CC-chart/activity.json', function(activity) {
        $.each(activity.datasets, function(i, dataset) {

            // Add X values
            dataset.data = Highcharts.map(dataset.data, function(val, j) {
                return [activity.xData[j], val];
            });

            $('<div class="chart">')
                .appendTo('#container')
                .highcharts('StockChart', {
                    chart: {
                //        renderTo: "container",
                     //   marginLeft: 40, // Keep all charts left aligned
                        spacingTop: 20,
                        spacingBottom: 20
                    },

                    rangeSelector: {
                       enabled: false,
                        //selected: 4,
                        //inputEnabled: true,
                        buttonTheme: {
                            visibility: 'hidden'
                        },
                        labelStyle: {
                            visibility: 'hidden'
                        }
                    },
                    title: {
                        text: dataset.name,
                        align: 'left',
                        margin: 0,
                        x: 40,
                        y: -1
                    },
                    subtitle: {
                        text: dataset.subname
                    },
                    credits: {
                        enabled: false
                    },
                    legend: {
                        align: 'right',
                        x: -40,
                        verticalAlign: 'top',
                        y: 45,
                        floating: true,
                        enabled: true
                    },

                    xAxis: {
                        type: 'datetime',
                        tickInterval: (24 * 3600 * 1000) / 2, // a day divided by 2
                        crosshair: true,
                        events: {
                            setExtremes: syncExtremes
                        },
                        labels: {
                            //     format: '{value} km'
                        }
                    },
                    navigator: {
                        enabled: (function() {
                            return i === 0
                        })(),

                        series: {
                            color: '#FFFFFF',
                            fillOpacity: 0.00,
                            lineWidth: 2
                        }
                    },
                    scrollbar: {
                        enabled: (function() {
                            return i === 0
                        })(),
                    },
                    yAxis: {

                      //  tickPixelInterval: 75,
                       // padding: -20,
                        reversed: (function() { return i === 0 })(),
                         max: dataset.max,
                         min: dataset.min,
                        endOnTick: true,
                        tickInterval: dataset.tickInterval,

                        opposite: false,
                         labels: {
                            enabled: true,
                             y: dataset.yOffset,
                           // step: 0,
                         },
                        title: {
                            //offset: 5,
                            text: dataset.yvalue,
                        }
                    },
                    tooltip: {
                        positioner: function() {
                            return {
                                x: this.chart.chartWidth - this.label.width, // right aligned
                                y: -1 // align to title
                            };
                        },
                        borderWidth: 0,
                        backgroundColor: 'none',
                        pointFormat: '{point.y}',
                        headerFormat: '',
                        shadow: false,
                        style: {
                            fontSize: '18px'
                        },
                        shared: false,
                        split: false,
                        valueDecimals: dataset.valueDecimals
                    },
                    series: [{
                        data: dataset.data,
                        name: dataset.name,
                        type: dataset.type,
                        color: Highcharts.getOptions().colors[i],
                        fillOpacity: 0.3,
                        tooltip: {
                            valueSuffix: ' ' + dataset.unit
                        }
                    }]
                });
        });
    });
});

最佳答案

我创建了一个简单的示例,说明如何在不编辑当前代码的情况下向图表添加其他系列:

JSON:

{
 "xData": [0,1,2,3,4], // the dates go here

 "datasets": [
  {
     "name": "Precipitation",

     "data": [2,2,2,2,2],     // data for precip go here
     "unit": "mm",
     "type": "area",
     "valueDecimals": 3
   },
   {
     "name": "Temperature",

     "data": [3,3,3,3,3],    // data for temp go here
     "unit": "°F",
     "type": "line",
     "valueDecimals": 2
  }
 ],
 "additionalDatasets": [
    {
     "name": "Additional series",

     "data": [1,1,1,1,1],     // data for precip go here
     "unit": "mm",
     "type": "line",
     "valueDecimals": 3
   }
 ]
}

附加JS代码:

    if (activity.additionalDatasets){
        activity.additionalDatasets.forEach(function(el, i){
            el.color = Highcharts.getOptions().colors[i+2]
            el.data = Highcharts.map(el.data, function(val, j) {
                return [activity.xData[j], val];
            });
        });
    }

...

                series: [{
                    data: dataset.data,
                    name: dataset.name,
                    type: dataset.type,
                    color: Highcharts.getOptions().colors[i],
                    fillOpacity: 0.3,
                    tooltip: {
                        valueSuffix: ' ' + dataset.unit
                    }
                }].concat(activity.additionalDatasets)

现场演示:https://jsfiddle.net/BlackLabel/gjLuk3zp/

关于javascript - Highchart - 将更多系列添加到多个同步的 Highstock 图表之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53312752/

相关文章:

javascript - 单击按钮创建按钮

javascript - 具有多种策略的 NuxtJs 身份验证,端点被覆盖

javascript - D3.js .rangeBands() 返回 'undefined' 仅包含最后一个值?

javascript - 如何获取 JavaScript 对象中给定键/值的路径?

json - 显示网络服务公开嵌套或平面列表?

javascript - 大数据集可视化

javascript - 在 Highcharts 中的最后一点动态绘制标记

json - 从types.JSON.TEXT转换为字符串列表

javascript - 使用缓冲区和流写入数据

ios - iOS Charts X Axis标签未全部显示