gpt4 book ai didi

jquery - 如何为 ChartJs Legend 添加标签

转载 作者:行者123 更新时间:2023-12-03 22:33:41 25 4
gpt4 key购买 nike

在 ChartJs 中,如何在图例上方添加文本/标签。我不需要图表的标签,但我需要将其放置在图例上方。

我正在使用ChartJs用于生成图表。

enter image description here

最佳答案

您可以使用 html 创建自定义图例。以下是如何使用自定义标题(和自定义用户界面)创建自定义图例的示例。

function legendClickCallback(event) {
event = event || window.event;

var target = event.target || event.srcElement;
while (target.nodeName !== 'LI') {
target = target.parentElement;
}
var parent = target.parentElement;
var chartId = parseInt(parent.classList[0].split("-")[0], 10);
var chart = Chart.instances[chartId];
var index = Array.prototype.slice.call(parent.children).indexOf(target);
var meta = chart.getDatasetMeta(index);

if (meta.hidden === null) {
meta.hidden = !chart.data.datasets[index].hidden;
target.classList.add('hidden');
} else {
target.classList.remove('hidden');
meta.hidden = null;
}
chart.update();
}

var ctx = document.getElementById("myChart");
var myLegendContainer = document.getElementById("myChartLegend");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["values #1", "values #2"],
datasets: [
{
label: "One",
backgroundColor: "red",
data: [26,36]
},
{
label: "Two",
backgroundColor: "blue",
data: [34, 40]
}

]
},
options: {
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});

myLegendContainer.innerHTML = myChart.generateLegend();
var legendItems = myLegendContainer.getElementsByTagName('li');
for (var i = 0; i < legendItems.length; i += 1) {
legendItems[i].addEventListener("click", legendClickCallback, false);
}
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
[class="0-legend"] {
cursor: pointer;
list-style: none;
padding-left: 0;
}
[class="0-legend"] li {
display: inline-block;
padding: 0 5px;
}
[class="0-legend"] li.hidden {
text-decoration: line-through;
}
[class="0-legend"] li span {
border-radius: 5px;
display: inline-block;
height: 10px;
margin-right: 10px;
width: 10px;
}
.legend-box{
border-color: gray;
border-style: dashed;
margin-top: 25px;
}
<script src="https://npmcdn.com/chart.js@latest/dist/Chart.bundle.min.js"></script>


<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"></canvas>
<div class='legend-box'>
<span>Chart legend</span>
<div id="myChartLegend"></div>
</div>
</div>
</body>
</html>

我使用了this example的代码创建上面的示例

关于jquery - 如何为 ChartJs Legend 添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51701465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com