ChartJS 图表js工具提示我的图表是显示所有数据作为一个组,而悬停在一个单一的酒吧

jm81lzqq  于 2023-04-30  发布在  Chart.js
关注(0)|答案(1)|浏览(156)

为什么会这样,请看下面的截图!
snap
我的数据从服务器上是一个数组的12大小的月份显示在标签上
“var sales = {{ $sales }};{{ $profit }};var loss = {{ $loss }};

//business trend monthly
    document.addEventListener("DOMContentLoaded", function() {
        // Line chart
        new Chart(document.getElementById("mychartjs"), {
            type: "bar",
            data: {
                labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
                datasets: [{
                label: "Sales",
                fill: true,
                backgroundColor: 'blue',
                borderWidth:0,
                data: sales
                },
                {
                label: "profit",
                fill: true,
                backgroundColor: "rgb(255, 78, 0)",
                borderWidth:0,
                data: profit
                },
                {
                label: "loss",
                fill: true,
                backgroundColor: "#dc3545",
                borderWidth:0,
                data: loss
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false,
                        boxWidth: 0
                    },
                    title: {
                        display: false,
                    }
                }
            }
        });
    });`
zbsbpyhn

zbsbpyhn1#

我不知道为什么会发生这种情况,因为当我运行您的代码时,工具提示总是只显示一个条形的值。但是,您可以显式定义options.plugins.tooltip.mode: 'nearest'(或任何其他合适的mode),以获得所需的行为。
有关详细信息,请参阅图表中的工具提示配置。js文档。
请看一下下面修改后的可运行代码。

const sales = [120, 130, 125, 132, 115, 96, 87, 92, 105, 111, 105, 142];
const profit = [12, 13, 5, 18, 6, 3, 0, 0, 0, 8, 13, 25];
const loss = [0, 0, 0, 0, 0, 0, 6, 12, 8, 0, 0, 0];

new Chart("mychartjs", {
  type: "bar",
  data: {
    labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    datasets: [{
        label: "Sales",
        backgroundColor: 'blue',
        borderWidth: 0,
        data: sales
      },
      {
        label: "profit",
        backgroundColor: "green",
        borderWidth: 0,
        data: profit
      },
      {
        label: "loss",
        backgroundColor: "red",
        borderWidth: 0,
        data: loss
      }
    ]
  },
  options: {
    plugins: {
      legend: {
        display: false,
        boxWidth: 0
      },
      title: {
        display: false,
      },
      tooltip: {
        mode: 'nearest'
      }
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@^4"></script>
<canvas id="mychartjs"></canvas>

相关问题