4

I am trying to build a synchronous charts but aligned horizontally, I did it based on

http://www.highcharts.com/demo/synchronized-charts

I made the alignment horizontal, now the charts are not synchronous

/*
The purpose of this demo is to demonstrate how multiple charts on the same page can be linked
through DOM and Highcharts events and API methods. It takes a standard Highcharts config with a
small variation for each data set, and a mouse/touch event handler to bind the charts together.
*/

$(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('https://www.highcharts.com/samples/data/jsonp.php?filename=activity.json&callback=?', 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" style="width:200px;float:left;">')
                .appendTo('#container')
                .highcharts({
                    chart: {
                        marginLeft: 40, // Keep all charts left aligned
                        spacingTop: 20,
                        spacingBottom: 20
                    },
                    title: {
                        text: dataset.name,
                        align: 'left',
                        margin: 0,
                        x: 30
                    },
                    credits: {
                        enabled: false
                    },
                    legend: {
                        enabled: false
                    },
                    xAxis: {
                        crosshair: true,
                        events: {
                            setExtremes: syncExtremes
                        },
                        labels: {
                            format: '{value} km'
                        }
                    },
                    yAxis: {
                        title: {
                            text: null
                        }
                    },
                    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'
                        },
                        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
                        }
                    }]
                });
        });
    });
});
.chart {
    
}
</style>
<!-- http://doc.jsfiddle.net/use/hacks.html#css-panel-hack -->
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container"></div>

Any help is much appricated,

Thanks in advance.

2 Answers 2

7

You could edit event.chartX after coordiantes are found in each chart by adding:

event.chartX = (event.chartX+600) % 200;

Adding 600 to avoid negative values and % by 200 because each chart has 200px of width. Example: http://jsfiddle.net/fzda6z8p/

Relevant part of code:

$('#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

        event.chartX = (event.chartX+600) % 200;

        point = chart.series[0].searchPoint(event, true); // Get the hovered point
        if (point) {
            point.highlight(e);
        }
    }
});
5
  • Nice.. Thank you... :) Jun 1, 2016 at 10:23
  • @kacper-madej, in my case charts are responsive; I have total 6 charts; two each row and for tablet / mobile devices one chart per row. I was able to access the chart's width via e.currentTarget.clientWidth, but what's the significance of '600' here? What it should be in my case? total number of charts each row * chart width? or some thing else?
    – Saif
    Apr 24, 2018 at 6:00
  • @kacper, I tried (event.chartX + 2 * e.currentTarget.clientWidth) % e.currentTarget.clientWidth this seems to work but in some cases some charts are one point ahead or behind of the others? e.g. some are at the second point / index where as others are at the third. is there any better approach you reckon?
    – Saif
    Apr 24, 2018 at 6:07
  • @SaifUllah Please add a live demo. It might be easier to run you case in a new SO question then to exchange information in comments here. Apr 26, 2018 at 10:33
  • @SaifUllah I am seeing the exact same issue as you - Did you find a solution? Thanks Jun 15, 2018 at 8:59
0

I have multiple series in each pair of charts. Sync fails when there are nulls in any of the series data.

This is a modified searchPoint function to find the exact category on X-Axis to be highlighted corresponding to the hovered point. So the crosshair moves smoothly even if there are blank values in the series.

function searchPoint(event, chart) {
    var points = chart.series[0].points,
        len = points.length,
        x = chart.axes[0].toValue(event.chartX),
        range = 0.2,
        pointX,
        i;

    for (i=0; i<len; i++) {
        pointX = points[i].x;
        if (x - range < pointX && pointX < x + range) {
            return points[i];
        }
    }
}

Forum discussion: https://www.highcharts.com/forum/viewtopic.php?t=35903

JSFiddle: https://jsfiddle.net/jj6a9jot/5/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.