首页 文章

在chart.js条形图上自定义工具提示

提问于
浏览
1

我想在chart.js条形图上自定义工具提示 . 这是我的代码:

$(function () {
  var barData = no_houses_person

var barOptions = {
    scaleBeginAtZero: true,
    scaleShowGridLines: true,
    scaleGridLineColor: "rgba(0,0,0,.05)",
    legend: {
        display: true,
        position: 'top'
    },
    scaleGridLineWidth: 1,
    barShowStroke: true,
    barStrokeWidth: 1,
    barValueSpacing: 5,
    barDatasetSpacing: 1,
    responsive: true,
};
   var ctx = document.getElementById("barChart").getContext("2d");
   var myNewChart = new Chart(ctx, {
    type: 'bar',
    data: barData,
    options: barOptions
});
});

我尝试将 tooltipTemplate: "<%if (label){%><%=label%> <%}%>(<%= value %> example)", 添加到barOptions但它没有任何效果 .

1 回答

  • 8

    Chart.js在v2中从模板移动到Object interfaces,所以例如如果你只想修改工具提示文本...

    tooltips: {
        callbacks: {
            label: function(tooltipItem) {
                return "$" + Number(tooltipItem.yLabel) + " and so worth it !";
            }
        }
    }
    

    结果:

    enter image description here

    Codepen:Chart.js Custom Tooltip

    有关更复杂的工具提示自定义,请在github上查看其示例:tooltips

相关问题