Высокие диаграммы: как переключаться между разными осями, имеющими отдельные полосы, кнопки выбора диапазона - PullRequest
0 голосов
/ 23 ноября 2018

У меня есть график с дневными значениями месяца октября.Две кнопки: неделя и месяц.Недельная сюжетная полоса должна совпадать с месячной сюжетной полосой: первые 2 дня имеют зеленый цвет, следующие 5 дней - синие в месячной полосе.При выборе недели диапазон дат 1-7 должен быть одинакового цвета: зеленый и синий.

Highcharts.chart('container', {
    chart: {
        type: 'column',
    },

    title: {
        text: 'How long time a TR has been placed in stages longer than 48 hours'
    },
    legend: {
        enabled: true
    },
    subtitle: {
        text: 'Input - verify should max be 48 hours = green zone'
    },

    data: {
        csv: document.getElementById('csv').innerHTML
    },

    plotOptions: {
        column: {

        },
        series: {
            dataLabels: {
                enabled: false,
                format: '{point.y}'
            }
        }
    },

    tooltip: {

    },

    rangeSelector: {
        buttonSpacing: 10,
        enabled: true,
        inputEnabled: false,
        selected: 1,
        buttons: [{
            type: 'week',
            count: 1,
            text: 'Week'
        }, {
            type: 'month',
            count: 1,
            text: 'Month'
        }],
    },
    xAxis: [{
        id: 'one',
        type: 'datetime',
        dateTimeLabelFormats: {
            millisecond: '%H:%M:%S.%L',
            second: '%H:%M:%S',
            minute: '%H:%M',
            hour: '%H:%M',
            day: '%e. %b',
            week: '%e. %b',
            month: '%b \'%y',
            year: '%Y'
        },

        plotBands: [{
            from: 1538352000000,
            to: 1538524800000,
            color: '#E8F5E9'

        }, {
            from: 1538524800000,
            to: 1538870400000,
            color: '#E0ECEC'
        }, {
            from: 1538870400000,
            to: 1539475200000,
            color: "#FFFDE7"
        }, {
            from: 1539475200000,
            to: 1540944000000,
            color: "#FFEBEE"
        }],
    }, {
        id: 'two',
        type: 'datetime',
        dateTimeLabelFormats: {
            millisecond: '%H:%M:%S.%L',
            second: '%H:%M:%S',
            minute: '%H:%M',
            hour: '%H:%M',
            day: '%e. %b',
            week: '%e. %b',
            month: '%b \'%y',
            year: '%Y'
        },

        plotBands: [{
            from: 1538352000000,
            to: 1538524800000,
            color: '#E8F5E9'

        }, {
            from: 1538524800000,
            to: 1538870400000,
            color: '#E0ECEC'
        }],
    }],

    yAxis: {
        min: 0,
        max: 100,
        title: {
            text: 'TRADING RECORDS',
        }
    }
});

См. jsfiddle

Существует ли способ переключения между двумяxaxis с разными plotBands: при нажатии на кнопку «неделя» отображается одна полоса, а при нажатии на кнопку «месяц» - другая полоса.То есть цвета сюжетной полосы относятся к датам?Я предполагаю, что должен использовать функции событий, такие как setExtremes и afterSetExtremes, но не знаете, как это сделать?Большое спасибо за помощь.

Мне удалось смоделировать вывод с помощью этой функции:

  events: {
    afterSetExtremes: function (e) {
        if (e.trigger == "rangeSelectorButton" &&
            e.rangeSelectorButton.text == "Week") {
            // it is your button that caused this,
            // so setExtrememes to your custom
            // have to do in timeout to let
            // highcharts finish processing events...
            setTimeout(function () {
                Highcharts.charts[0].xAxis[0].setExtremes(1538352000000, 1538524800000)
            }, 1);

        }


    },
}

Но это работает только при выборе конкретного: setExtremes (1538352000000, 1538524800000) Я думаю, что для масштабируемого решения на любые 7 дней потребуетсякакая-то функциональность исключений для удаления текущего диапазона на xaxis с addplotband

Обновлено fiddle

1 Ответ

0 голосов
/ 30 ноября 2018

Вместо этого я добавил пользовательские кнопки: https://forum.highcharts.com/viewtopic.php?t=31649

    <div class="btn-group" data-toggle="buttons">
         <button class="btn btn-custom" id="one">48 hours</button>
         <button class="btn btn-custom" id="two">7 days</button>
         <button class="btn btn-custom" id="three">14 days</button>
         <button class="btn btn-custom" id="four">31 days</button>
         <button class="btn btn-custom" id="all">All</button>
   </div>

    <div id="containerbenchmark"></div>

$.get('bm.csv', function (bmcsv) {

    var chart = new Highcharts.Chart({

        chart: {
            renderTo: 'containerbenchmark',
            type: 'areaspline',
        },

        title: {
            text: ''
        },
        legend: {
            enabled: true
        },
        subtitle: {
            text: 'Input - verify - close should max be 48 hours = green zone'
        },

        data: {
            csv: bmcsv,
        },

        plotOptions: {
            areaspline: {
                stacking: 'normal'
            },
            series: {
                dataLabels: {
                    enabled: false,
                    format: '{point.y}'
                }
            }
        },

        tooltip: {
            /*headerFormat: '<span style="font-size: 16px">{point.key}</span><br/>',    
            pointFormat: '<span style="font-size: 14px; color:{series.color}">{series.name}: <span style="font-size: 14px">{point.y} {point.total}</span><br/>',
            footerFormat:  '<span style="font-size: 16px">{point.total}</span><br/>',*/
            shared: true,
            useHTML: true,
            formatter: function () {
                var tooltip = '<table><span style="font-size: 16px">' + Highcharts.dateFormat('%e/%b/%Y',
                    new Date(this.x)) + '</span><br/><tbody>';
                //loop each point in this.points
                $.each(this.points, function (i, point) {
                    tooltip += '<tr><th style="font-size: 14px; color: ' + point.series.color + '">' + point.series.name + ': </th>' +
                        '<td style="font-size: 14px; text-align: right">' + point.y + '</td></tr>'
                });
                tooltip += '<tr><th style="font-size: 16px">Total: </th>' +
                    '<td style="font-size: 16px; text-align:right"><span>' + this.points[0].total + '</span></td></tr>' +
                    '</tbody></table>';
                return tooltip;
            }
        },

        rangeSelector: {
            selected: 2,
            enabled: true,
            inputEnabled: true,
            inputDateFormat: "%m/%d/%Y",
            inputEditDateFormat: "%m/%d/%Y",
            inputDateParser: function (s) {
                return Date.UTC(
                    parseInt(s.substr(6, 4)),
                    parseInt(s.substr(0, 2) - 1),
                    parseInt(s.substr(3, 2)),
                    12
                )
            }
        },

        navigator: {
            enabled: true
        },

        xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: {
                millisecond: '%H:%M:%S.%L',
                second: '%H:%M:%S',
                minute: '%H:%M',
                hour: '%H:%M',
                day: '%e. %b',
                week: '%e. %b',
                month: '%b \'%y',
                year: '%Y'
            },

            plotBands: [{
                from: 1538352000000,
                to: 1538524800000,
                color: '#cae8cc',
                label: {
                    text: '> 48 hours',
                    style: {
                        color: 'black',
                        fontWeight: 'bold',
                        textTransform: 'uppercase',
                        fontSize: '14px'
                    }
                }
            }, {
                from: 1538524800000,
                to: 1538870400000,
                color: '#d0e2e2',
                label: {
                    text: '> 7 days',
                    style: {
                        color: 'black',
                        fontWeight: 'bold',
                        textTransform: 'uppercase',
                        fontSize: '14px'
                    }
                }
            }, {
                from: 1538870400000,
                to: 1539475200000,
                color: "#fff9b3",
                label: {
                    text: '> 14 days',
                    style: {
                        color: 'black',
                        fontWeight: 'bold',
                        textTransform: 'uppercase',
                        fontSize: '14px'
                    }
                }
            }, {
                from: 1539475200000,
                to: 1540944000000,
                color: "#ffb3be",
                label: {
                    text: '> 31 days',
                    style: {
                        color: 'black',
                        fontWeight: 'bold',
                        textTransform: 'uppercase',
                        fontSize: '14px'
                    }
                }
            }],


        },

        yAxis: {
            min: 0,
            title: {
                text: 'TRADING RECORDS',
            }
        }
    }, function (chart) {

        // apply the date pickers
        setTimeout(function () {
            var rangeSelector = $('#containerbenchmark input.highcharts-range-selector');

            rangeSelector.datepicker({
                autoclose: true,
                todayHighlight: true
            }) /*.datepicker('update', new Date())*/ ;

            var inputMin = rangeSelector.filter('[name=min]');
            var inputMax = rangeSelector.filter('[name=max]');

            inputMin.datepicker().on("changeDate", function (event) {
                console.log(inputMin.datepicker("getDate"));
                console.log(inputMin.datepicker("getUTCDate"));
            });
        }, 1000);
    });

    $('#one').click(function () {
        toggleActiveState(false);
        chart.xAxis[0].setExtremes(
            1538352000000,
            1538524800000
        );
    });
    $('#two').click(function () {
        toggleActiveState(false);
        chart.xAxis[0].setExtremes(
            1538524800000,
            1538870400000
        );
    });
    $('#three').click(function () {
        toggleActiveState(false);
        chart.xAxis[0].setExtremes(
            1538870400000,
            1539475200000
        );
    });
    $('#four').click(function () {
        toggleActiveState(false);
        chart.xAxis[0].setExtremes(
            1539475200000,
            1540944000000
        );
    });
    $('#all').click(function () {
        chart.xAxis[0].setExtremes(
            event.min,
            event.max
        );
    });
});
...