gpt4 book ai didi

javascript - 如何在 ChartJS 中创建自定义图例

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:41 24 4
gpt4 key购买 nike

我需要使用 ChartJS 库为我的圆环图创建自定义图例。我已经使用 ChartJS 提供的默认图例创建了 donut ,但我需要进行一些修改。

我想在车名之上设置值。另外,我不喜欢粘性图例,我想让它与 donut 分开,这样我就可以更改字体、框的样式(例如,在文本“Audi”旁边)

我知道有一些 Legend generator但我不确定如何将它与 VueJS 一起使用 - 因为我使用 VueJS 作为框架

这就是我的传奇现在的样子 - http://imgur.com/a/NPUoi

我的代码:

从我导入 donut 组件的 Vue 组件:

<div class="col-md-6">
<div class="chart-box">
<p class="chart-title">Cars</p>
<donut-message id="chart-parent"></donut-message>
</div>
</div>

Javascript:

    import { Doughnut } from 'vue-chartjs'
export default Doughnut.extend({

ready () {


Chart.defaults.global.tooltips.enabled = false;
Chart.defaults.global.legend.display = false;

this.render({
labels: ['Audi','BMW','Ford','Opel'],
datasets: [
{
label: 'Cars',
backgroundColor: ['#35d89b','#4676ea','#fba545','#e6ebfd'],
data: [40, 30, 20, 10]
}
]
},
{
responsive: true,
cutoutPercentage: 75,
legend: {
display: true,
position: "right",
fullWidth: true,
labels: {
boxWidth: 10,
fontSize: 14
}
},
animation: {
animateScale: true
}
})
}
});

最佳答案

我在尝试理解文档时遇到了同样的问题,此链接可能会阐明自定义图例的过程:

https://codepen.io/michiel-nuovo/pen/RRaRRv

诀窍是跟踪回调以构建您自己的 HTML 结构并将此新结构返回给 ChartJS。

在选项对象内:

legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets[0].data.length; i++) {
text.push('<li><span style="background-color:' +
chart.data.datasets[0].backgroundColor[i] + '">');
if (chart.data.labels[i]) {
text.push(chart.data.labels[i]);
}
text.push('</span></li>');
}
text.push('</ul>');
return text.join("");
}

其次,您需要一个容器来插入新的 html 并使用方法 myChart.generateLegend() 来获取自定义的 html:

$("#your-legend-container").html(myChart.generateLegend());

之后,如果需要,跟踪事件:

$("#your-legend-container").on('click', "li", function() {
myChart.data.datasets[0].data[$(this).index()] += 50;
myChart.update();
console.log('legend: ' + data.datasets[0].data[$(this).index()]);
});

$('#myChart').on('click', function(evt) {
var activePoints = myChart.getElementsAtEvent(evt);
var firstPoint = activePoints[0];
if (firstPoint !== undefined) {
console.log('canvas: ' +
data.datasets[firstPoint._datasetIndex].data[firstPoint._index]);
}
else {
myChart.data.labels.push("New");
myChart.data.datasets[0].data.push(100);
myChart.data.datasets[0].backgroundColor.push("red");
myChart.options.animation.animateRotate = false;
myChart.options.animation.animateScale = false;
myChart.update();
$("#your-legend-container").html(myChart.generateLegend());
}
}

我发现的另一个解决方案,如果您不需要更改图例中的 HTMl 结构,您可以在图例容器中插入相同的 HTML 并通过 CSS 对其进行自定义,请查看另一个链接:

http://jsfiddle.net/vrwjfg9z/

希望它对你有用。

关于javascript - 如何在 ChartJS 中创建自定义图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44649247/

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