Chartjs v2.8 showAllTooltips не существует - PullRequest
0 голосов
/ 01 июля 2019

У меня есть диаграмма, созданная с использованием chart.js версии 2.8, работающей в приложении Angular. Мне нужны всплывающие подсказки, чтобы они всегда были видны на графике по умолчанию, а не только тогда, когда курсор мыши находится над точками (диаграмма представляет собой точечный график). Я рассмотрел, как это настроить, и большинство источников рекомендуют использовать pluginService для регистрации исправления, чтобы включить эту возможность. Однако файл chart.config.options.showAllTooltips должен уже существовать, тогда как его больше нет в chart.js v2.8.

this.LQChart = new Chart(this.myChart, {
                type: 'bubble',
                data: {
                    labels:['Jobs']
                }, options: {
                    plugins:{
                        colorschemes: {
                            scheme: 'brewer.YlOrBr9'
                        },
                        zoom:{
                            pan: {
                                enabled: true,
                                mode: 'xy',
                                rangeMin: {
                                    x: null,
                                    y: null
                                },
                                rangeMax:{
                                    x: null,
                                    y: null
                                }
                            },
                            zoom:{
                                enabled: true,
                                drag: false,
                                mode:'xy',
                                rangeMin: {
                                    x: null,
                                    y: null
                                },
                                rangeMax:{
                                    x: null,
                                    y: null
                                },
                                speed:0.1
                            }
                        },
                        // datalabels: {
                        //     color: 'white',
                        //     font: {
                        //         weight:'bold'
                        //     },
                        //     display: function (context) {
                        //         console.log("Algo: "+context);
                        //         return context.dataset.data[context.dataIndex] > 15;
                        //     },
                        //     formatter: function(value, context) {
                        //         console.log("Forma: "+value+" : "+context);
                        //         return context.dataIndex + ':' + Math.round(value*100) + '%';
                        //     }
                        // }
                    }, tooltips: {
                        callbacks: {
                            label: function(tooltipItem, data) {
                                var label = data.datasets[tooltipItem.datasetIndex].label || '';
                                return label
                            }
                        }
                    },legend: {
                        display: false
                    }, title: {
                        display: true,
                        text: 'Location Quotient of Jobs in Region'
                    }, scales: {
                        yAxes: [{ 
                            scaleLabel: {
                                display: true,
                                labelString: "# of Jobs"
                            },
                            id:'y-axis-0',
                            type:'linear',
                            gridLines: {
                                display:true
                            },
                            ticks: {
                                callback: function(value, index, values) {
                                    return Number(value.toString());
                                }
                            },
                            position:'left'
                        }],
                        xAxes: [{
                            scaleLabel: {
                                display: true,
                                labelString: "LQ"
                            },
                            id: 'x-axis-0',
                            type: 'linear',
                            position: 'bottom',
                        }]
                    }, annotation: {
                        annotations: [{
                            borderColor: 'black',
                            //borderDash: [2, 2],
                            borderWidth: 2,
                            mode: 'vertical',
                            type: 'line',
                            value: 1.0,
                            scaleID: 'x-axis-0'
                        }]
                    }
                }
            });

Это код, который я использую для создания своей диаграммы, мне просто нужно знать, как установить всплывающие подсказки для диаграммы всегда *. 1004 *

Ответы [ 2 ]

1 голос
/ 01 июля 2019

В V2 ChartJ было много дискуссий по этому вопросу, которые вы можете найти здесь , здесь и здесь .

В общем, вам нужно зарегистрировать свой собственный плагин для ChartJ, который вы затем сможете использовать через свойство options.

Так что, если вы добавите следующий плагин регистрации:

Chart.pluginService.register({
            beforeRender: function (chart) {
                if (chart.config.options.showAllTooltips) {
                    // create an array of tooltips
                    // we can't use the chart tooltip because there is only one tooltip per chart
                    chart.pluginTooltips = [];
                    chart.config.data.datasets.forEach(function (dataset, i) {
                        chart.getDatasetMeta(i).data.forEach(function (sector, j) {
                            chart.pluginTooltips.push(new Chart.Tooltip({
                                _chart: chart.chart,
                                _chartInstance: chart,
                                _data: chart.data,
                                _options: chart.options.tooltips,
                                _active: [sector]
                            }, chart));
                        });
                    });

                    // turn off normal tooltips
                    chart.options.tooltips.enabled = false;
                }
            },
            afterDraw: function (chart, easing) {
                if (chart.config.options.showAllTooltips) {
                    // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
                    if (!chart.allTooltipsOnce) {
                        if (easing !== 1)
                            return;
                        chart.allTooltipsOnce = true;
                    }

                    // turn on tooltips
                    chart.options.tooltips.enabled = true;
                    Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
                        tooltip.initialize();
                        tooltip.update();
                        // we don't actually need this since we are not animating tooltips
                        tooltip.pivot();
                        tooltip.transition(easing).draw();
                    });
                    chart.options.tooltips.enabled = false;
                }
            }
        })

Затем вы можете добавить свойство showAllTooltips в options следующим образом:

options: {
        showAllTooltips: true
        ...

Взгляните на эту иллюстрацию вашего кода с некоторыми примерами данных.

0 голосов
/ 01 июля 2019

Викас определенно дал мне правильный ответ, но я хотел изменить следующее: Если у кого-то возникла та же проблема, что и у меня, когда код pluginService.register выдает всевозможные ошибки, я хочу опубликовать здесь свой регистрационный код после изменения:

Chart.pluginService.register({
    beforeRender: function (chart) {
        if (chart.config.options['showAllTooltips']) {
            // create an array of tooltips
            // we can't use the chart tooltip because there is only one tooltip per chart
            chart['pluginTooltips'] = [];
            chart.config.data.datasets.forEach(function (dataset, i) {
                chart.getDatasetMeta(i).data.forEach(function (sector, j) {
                    chart['pluginTooltips'].push(new (Chart as any).Tooltip({
                        _chart: chart['chart'],
                        _chartInstance: chart,
                        _data: chart.data,
                        _options: chart['options']['tooltips'],
                        _active: [sector]
                    }, chart));
                });
            });

            // turn off normal tooltips
            chart['options']['tooltips']['enabled'] = false;
        }
    },
    afterDraw: function (chart, easing: any) {
        if (chart.config.options['showAllTooltips']) {
            // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
            if (!chart['allTooltipsOnce']) {
                if (easing !== 1)
                    return;
                chart['allTooltipsOnce'] = true;
            }

            // turn on tooltips
            chart['options']['tooltips']['enabled'] = true;
            Chart.helpers.each(chart['pluginTooltips'], function (tooltip) {
                tooltip.initialize();
                tooltip.update();
                // we don't actually need this since we are not animating tooltips
                tooltip.pivot();
                tooltip.transition(easing).draw();
            });
            chart['options']['tooltips']['enabled'] = false;
        }
    }
})

Это сработало для меня, и я надеюсь, что любой, кто столкнется с той же проблемой, найдет это полезным.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...