Chart.JS 工具提示回调标签和标题 (v3.5)。

8
请注意:有很多版本是针对v2的答案,这个答案适用于v3。
我正在尝试设置一个甜甜圈图表的提示文本标签和标题。
代码:
        //Create the donut chart
    donut = new Chart('questions_positivity_donut', {
        type: 'doughnut',
        data: { 
            labels: ["Positive", "Other"],
            datasets: [{
                label: 'Sentiment',
                data: [user_context.state.avg_joy, (1-user_context.state.avg_joy)],
                backgroundColor: ['#a9a9a9','#f2f2f2']
            }]
        },
        options: {
            cutout: "70%",
            plugins: {
                legend: {
                    display: false
                },
                maintainAspectRatio: false,
                responsive: true,
                tooltip: {
                    callbacks: {
                        label: function(context) {

                            let label = new Intl.NumberFormat('en-US', {style: 'percent', minimumFractionDigits: 0, maximumFractionDigits: 0}).format(context.formattedValue);
                            return label;
                        },
                        title: function(context) {

                            let title = context.parsed.x;
                            return title;
                        } 
                    },
                    displayColors: false
                }                   
            }
        }
    }); 

如何在tooltip.callback中返回正确的标题?

例如:“Positive 35%”和“Other 65%”

1个回答

11

如果记录上下文,您会看到它是一个包含对象的数组,在使用默认交互模式时,它只包含一个项目,因此您可以选择该项目,然后像这样访问其中的

var options = {
  type: 'doughnut',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
    }]
  },
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          label: function(context) {

            let label = new Intl.NumberFormat('en-US', {
              style: 'percent',
              minimumFractionDigits: 0,
              maximumFractionDigits: 0
            }).format(context.formattedValue);
            return label;
          },
          title: function(context) {
            let title = context[0].label;
            return title;
          }
        },
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>


我尝试了一下,但出现了这个错误:TypeError: Converting circular structure to JSON - Izzi
看起来运行得很好,如果不行,请分享一个可重现的样例。 - LeeLenalee
抱歉,我是指 console.log。是的 - 完美!已接受!谢谢。 - Izzi
你是怎么记录这个的?我一直在尝试但还是失败了。 - Izzi
3
@Izzi 抱歉回复晚了,但我只是这样写的:console.log(context) - LeeLenalee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接