簡體   English   中英

ChartJS 自定義圖例甜甜圈將圖例與圖表區域分開

[英]ChartJS custom legend doughnut separate legend from chart area

我正在嘗試將LegendChartJS Chart中的圖表分開。 使用“默認”圖例時,無法控制圖表區域的大小,並且我的圖例中的項目越多,它就會變得越小......

如果可以在不更改Chart Area大小的情況下擴展Legend ,我很想聽聽任何這樣做的人:)

我正在嘗試的另一個選項是創建一個自定義Legend並將其插入為 innerHTML,並隱藏默認圖例。

我嘗試了使用legendCallback的解決方案,例如:

示例 1

示例 2

示例 3

但他們都對我不起作用......不知道為什么,我已經完全按照他們指定的方式完成了。

我認為這可能是ChartJS的版本(我使用的是最新版本)或其他一些阻止圖例顯示的數據問題。

我的代碼:

var chart1 = document.getElementById('displayVals').getContext('2d');
var mychart1 = new Chart(chart1, {
    type: 'doughnut',
    data: {
        labels: namelist,
        datasets: [{
            label: 'Doughnut Chart :)',
            data: valuelist,
            backgroundColor: GraphColors,
            borderWidth: 0
        }]
    },
    options: {
        layout: {
            padding: chartPadding
        },
        responsive: true,
        maintainAspectRatio: false,

        legend: {
            display: false
        },
        legendCallback: function (chart) {
            var text = [];
            text.push('<ul class="0-legend">');
            var ds = chart.data.datasets[0];
            var sum = ds.data.reduce(function add(a, b) { return a + b; }, 0);
            for (var i = 0; i < ds.data.length; i++) {
                text.push('<li>');
                var perc = Math.round(100 * ds.data[i] / sum, 0);
                text.push('<span style="background-color:' + ds.backgroundColor[i] + '">' + '</span>' + chart.data.labels[i] + ' (' + ds.data[i] + ') (' + perc + '%)');
                text.push('</li>');
            }
            text.push('</ul>');
            return text.join("");
        },

        plugins: {
            title: {
                display: true,                  
                text: 'Names',
                color: titleColor,
                padding: titlePadding,
                font: {
                    family: fontFamily,
                    size: fontSize,
                    style: fontStyle
                }
            }
        }
    }
})

var myLegendContainer = document.getElementById("legend1");
myLegendContainer.innerHTML = mychart1.generateLegend();

和 html:

<div class="container">
    <div class="row">
        <div class="col-4">
            <div>
                <canvas class="doughnutChart" id="displayVals"></canvas>
            </div>
            <div id="legend1">test</div>
        </div>
</div>

我可以在其中顯示“測試”一詞,但僅此而已...

有任何想法嗎..?

Legends 命名空間在 V3 中已更改,現在已在plugins部分配置,您還配置了標題。

要實現外部圖例,您需要使用自定義插件,您還需要在插件部分進行配置。

您可以從這個官方示例中復制粘貼插件: https://www.chartjs.org/docs/master/samples/legend/html.html

您需要配置的唯一內容是:

  • 對於內部圖例插件,您需要禁用它
  • 對於自定義圖例插件,您需要為其提供生成圖例所需的 div 的 ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM