猿问

饼图.js-显示无数据保留消息

我正在使用chart.js版本:2.8.0来显示条形图和饼图。


非空的条形图和饼图根据需要显示。


但是,当条形图和饼形图为空或要显示零数据时,是否有标准化的选项来显示“无数据可显示!”。条形图和饼形图的消息都可以显示,以代替空白数据或零数据。


我已经在Google上搜索了插件,并在SO中找到了解决方案,但是我发现的选项根本不起作用,或者不适用于最新版本的chartjs。


这是我的空饼图:


new Chart(document.getElementById('pieChartExample01'), {

    type: 'pie',

    data: {

        labels: [

            'Views',

            'Print Requests',

            'PDF Downloads',

            'DOCX Downloads',

        ],

        datasets: [{

            backgroundColor: [

                'rgba(71, 101, 160, 0.3)',  // #4765a0.

                'rgba(0, 0, 0, 0.3)',  // #000000.

                'rgba(52, 137, 219, 0.3)',  // #3489db.

                'rgba(179, 179, 179, 0.3)',  // #b3b3b3.

            ],

            hoverBackgroundColor: [

                'rgba(71, 101, 160, 0.6)',  // #4765a0.

                'rgba(0, 0, 0, 0.6)',  // #000000.

                'rgba(52, 137, 219, 0.6)',  // #3489db.

                'rgba(179, 179, 179, 0.6)',  // #b3b3b3.

            ],

            borderWidth: 1,

            hoverBorderWidth: 2,

            borderColor: [

                'rgba(71, 101, 160, 1)',  // #4765a0.

                'rgba(0, 0, 0, 1)',  // #000000.

                'rgba(52, 137, 219, 1)',  // #3489db.

                'rgba(179, 179, 179, 1)',  // #b3b3b3.

            ],

            borderAlign: 'inner',

            data: [0, 0, 0, 0]

      }]

    },

    options: {

        title: {

          display: false,

          text: 'Overall Activity'

        }

    }

});

<canvas id="pieChartExample01" width="25" height="25"></canvas>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

这就是我希望空饼图显示为(最好带有标签)的内容:


慕丝7291255
浏览 211回答 3
3回答

狐的传说

使用我稍加修改的该插件,该插件检查每个数据集项是否为零:<script>&nbsp; &nbsp; Chart.plugins.register({&nbsp; &nbsp; &nbsp; &nbsp; afterDraw: function(chart) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (chart.data.datasets[0].data.every(item => item === 0)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let ctx = chart.chart.ctx;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let width = chart.chart.width;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let height = chart.chart.height;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; chart.clear();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.save();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.textAlign = 'center';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.textBaseline = 'middle';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.fillText('No data to display', width / 2, height / 2);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx.restore();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });</script>这样,如果所有数据集项目均为0,它将No data to display代替图表显示。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答