ChartJS-设置与x轴描述不同的悬停文本

2022-02-24 00:00:00 javascript chart.js

我正在使用chartjs来可视化条形图中的一些数据。标签很长,所以我把它们剪掉了。但是,我希望工具提示的文本(悬停时)是原始的。我可以使用默认的chartjs配置实现这一点吗?

我使用以下内容来生成图表:

function DrawChart(canvasID, remoteFields, remoteData, remoteColors, remoteBorderColors) {
    var ctx = document.getElementById(canvasID).getContext('2d');

    var orig = remoteFields;
    var maxLabelLength = 20;
    for(var i = 0; i < remoteFields.length; i++) {
        if(remoteFields[i].length > maxLabelLength) {
            remoteFields[i] = remoteFields[i].substring(0,maxLabelLength) + "...";
        }
    }
    var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
    labels: remoteFields,
        datasets: [{
            data: remoteData,
            backgroundColor: remoteColors,
            borderColor: remoteBorderColors,
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true,
                    stepSize: 1
                }
            }]
        },
        responsive: true,
        maintainAspectRatio: false,
        legend: {
        display: false
    }
    }
});
}

解决方案

可以使用勾选回调函数(用于裁剪x轴标签)和tooltips callback函数(在工具提示上显示原始文本)

var ctx = document.getElementById('c').getContext('2d');
var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['January', 'February', 'March', 'April', 'May'],
      datasets: [{
         data: [1, 2, 3, 4, 5],
         backgroundColor: ['#30799f', '#ac51c3', '#4ba57b', '#e3297d', '#e35c32'],
         borderColor: ['#30799f', '#ac51c3', '#4ba57b', '#e3297d', '#e35c32'],
         borderWidth: 1
      }]
   },
   options: {
      responsive: false,
      scales: {
         xAxes: [{
            ticks: {
               callback: function(t) {
                  var maxLabelLength = 3;
                  if (t.length > maxLabelLength) return t.substr(0, maxLabelLength) + '...';
                  else return t;
               }
            }
         }],
         yAxes: [{
            ticks: {
               beginAtZero: true,
               stepSize: 1
            }
         }]
      },
      legend: {
         display: false
      },
      tooltips: {
         callbacks: {
            title: function(t, d) {
               return d.labels[t[0].index];
            }
         }
      }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="c" width="350" height="200"></canvas>

相关文章