如何隐藏图表工具提示的标题?

17

我正在使用Chart.js显示分组柱形图,并尝试隐藏工具提示的标题。

生成柱状图的代码

var ctx = document.getElementById("myChart").getContext("2d");

var data = {
    labels: ["Chocolate", "Vanilla", "Strawberry"],
    datasets: [
        {
            label: "Blue",
            backgroundColor: "blue",
            data: [3,7,4]
        },
        {
            label: "Red",
            backgroundColor: "red",
            data: [4,3,5]
        },
        {
            label: "Green",
            backgroundColor: "green",
            data: [7,2,6]
        }
    ]
};

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: data,
    options: {
        barValueSpacing: 20,
        scales: {
            yAxes: [{
                ticks: {
                    min: 0,
                }
            }]
        }
    }
});

在工具提示中显示标签“巧克力,香草,草莓”,我试图使用以下方法隐藏标签

将标题字体大小设置为0,但它没有起作用。

tooltipTitleFontSize: 0

我已经尝试使用工具提示回调函数,它会禁用标签蓝色、红色和绿色,但我不需要那个。

 tooltips: {
        callbacks: {
           label: function(tooltipItem) {
                  return tooltipItem.yLabel;
           }
        }
    }

事先感谢您的帮助。


https://stackoverflow.com/questions/35431733/i-want-to-hide-the-label-in-tooltip-because-it-showing-undefined - Nimish
我已经尝试过了,但它不起作用。 - Arun Kumaresh
3个回答

39

要隐藏工具提示的标题,您需要在工具提示标题的回调函数中返回一个空函数,像这样...

options: {
   tooltips: {
      callbacks: {
         title: function() {}
      }
   },
   ...
}

嗨,我遇到了一个错误 Types of property 'title' are incompatible. 我按照你提到的方法将它放在回调函数中。 - infodev
该函数需要返回某些内容。只需返回null即可正常工作。请参见此处:https://stackoverflow.com/a/62190418/756458 - BoDeX
Chart.js 4.4,需要返回空字符串。 - undefined

8
为了隐藏工具提示的标题/标签,应该将其添加到该图表的选项对象中,如下所示:
options: {
   plugins: {
      tooltip: {
         callbacks: {
            title : () => null // or function () { return null; }
         }
      }
   }
}

请参考文档以更好地了解应该使用自定义回调函数来处理它,这不是可以直接在选项中设置的配置。https://www.chartjs.org/docs/latest/configuration/tooltip.html#tooltip-callbacks 我在另一个主题中也提到了同样的问题:https://stackoverflow.com/a/68033933/8578337

1
这种方法更准确,否则eslint会给出此错误。Unexpected empty method 'title'.eslint@typescript-eslint/no-empty-function -- 点击查看详情 链接 - Mehmet Mücahit Çağlıyan

1
根据Chart.js 4.3.1文档中的Tooltip Callbacks部分所述:
如果回调函数返回undefined,则将使用默认的回调函数。如果要从工具提示中删除内容,回调函数应返回一个空字符串。
{
    options: {
        plugins: {
            tooltip: {
                // ...other options
                callbacks: {
                    title: () => ''
                }
            }
        }
    }
}

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