如何在Chart.JS的半甜甜圈图中间添加一些文本?

时间:2019-04-01 15:52:23

标签: javascript chart.js

它看起来应该像这样:

我已经有了图表,只是缺少文本。可以在图表中间获取文本吗?

编辑:可以在此处找到这种图形的示例:https://jsfiddle.net/wt4260qf/1/

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            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: {
        rotation: 1 * Math.PI,
        circumference: 1 * Math.PI
    }
});

enter image description here

2 个答案:

答案 0 :(得分:2)

感谢@DTul,我知道了。标题配置在这里:https://www.chartjs.org/docs/latest/configuration/title.html

我添加了以下部分:

title: {
   display: true,
   text: 'Custom Chart Title',
   position: 'bottom'
}

options

整个示例现在看起来像这样:

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'doughnut',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            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: {
        rotation: 1 * Math.PI,
        circumference: 1 * Math.PI,
        title: {
           display: true,
           text: 'Custom Chart Title',
           position: 'bottom'
        }
     }
});

相应的小提琴在这里:https://jsfiddle.net/ktq8mb0z/

答案 1 :(得分:0)

我使用了此说明

How can I add some text in the middle of a half doughnut chart in Chart.JS?

文本位置和字体大小的一些更改

var fontSizeToUse = 16;
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) - 80);

http://jsfiddle.net/vencendor/e0c8rgbm/