# 图例与提示框

URL: https://caijiao.org/chartjs/04-styling/04-legend-tooltip
Source: docs/chartjs/04-styling/04-legend-tooltip.md
Description: 介绍如何配置和自定义 Chart.js 图表中的图例（Legend）和提示框（Tooltip），提升数据展示的交互性和用户体验。

[Chart.js](/chartjs/) 提供灵活的图例和提示框配置，方便你展示图表信息。图例可以控制显示与隐藏、调整位置和样式，提示框则支持丰富的内容格式和交互效果，帮助用户更好理解图表数据。

```js
(function () {
  const ctx = document.getElementById("legendTooltipChart").getContext("2d");
  const legendTooltipChart = new Chart(ctx, {
    type: "bar",
    data: {
      labels: ["苹果", "香蕉", "橙子", "葡萄", "草莓"],
      datasets: [
        {
          label: "水果销量",
          data: [12, 19, 7, 15, 10],
          backgroundColor: [
            "rgba(255, 99, 132, 0.7)",
            "rgba(255, 206, 86, 0.7)",
            "rgba(54, 162, 235, 0.7)",
            "rgba(153, 102, 255, 0.7)",
            "rgba(75, 192, 192, 0.7)",
          ],
        },
      ],
    },
    options: {
      responsive: true,
      plugins: {
        legend: {
          display: true,
          position: "top",
          labels: {
            color: "#444",
            font: { size: 14 },
          },
          onClick: (e, legendItem, legend) => {
            const index = legendItem.datasetIndex;
            const ci = legend.chart;
            ci.toggleDataVisibility(index);
            ci.update();
          },
        },
        tooltip: {
          enabled: true,
          backgroundColor: "rgba(0,0,0,0.8)",
          titleFont: { size: 16, weight: "bold" },
          bodyFont: { size: 14 },
          callbacks: {
            label: function (context) {
              return `销量: ${context.parsed.y}`;
            },
          },
        },
      },
    },
  });
})();
```

[在线代码演示](/chartjs/demos/14.html)
