在酒吧的顶端图表JS显示数据值

问题描述 投票:0回答:1

我米,CHART JS begginning和我有一个问题,当我想显示在每个柱顶部的数据值,当我的鼠标悬停是酒吧的价值消失。接下来的问题是价值被裁剪在图表的顶部

这里是我的代码:

function assignChart(ctx, dataArray) {
    const dataLabel = ["Paris", "Milan", "London", "Florence", "New York", "Not specified"];

    return (new Chart(ctx, {
        type: 'bar',
        data: {
            labels: dataLabel,
            datasets: [{
                data: dataArray,
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            events: [],
            responsive: true,
            maintainAspectRatio: false,
            legend: {
                display: false
            },
            scales: {
                yAxes: [{
                    ticks: {
                        display: false,
                        beginAtZero:true,
                    }
                }]
            },
            animation: {
                duration : 1,
                onComplete : function() {
                    var chartInstance = this.chart,
                    ctx = chartInstance.ctx;

                    ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'bottom';

                    this.data.datasets.forEach(function(dataset, i) {
                        var meta = chartInstance.controller.getDatasetMeta(i);
                        meta.data.forEach(function(bar, index) {
                            if (dataset.data[index] > 0) {
                                var data = dataset.data[index];
                                ctx.fillText(data, bar._model.x, bar._model.y);
                            }
                        });
                    });
                }
            }
        }
    }));
}

PS:我正在使用ChartJS 2.7.3

javascript jquery chart.js
1个回答
2
投票

对于顶部的数据标签越来越裁剪你的问题,你可以通过这样的布局选项来增加填充:

layout: {
      padding: {
        left: 0,
        right: 0,
        top: 15,
        bottom: 0
      }
    }

见小提琴 - > https://jsfiddle.net/xys1tqfn/1/

© www.soinside.com 2019 - 2024. All rights reserved.