首页 > 解决方案 > ChartJs 折线图 - 在某些数据点上方显示永久图标,并在悬停时显示文本

问题描述

我有一个需要绘制的图表,除了数据点之外,我还想要一个带有自定义文本字符串的(某些)数据点上方永久的图标。

我不需要默认值弹出框,因为我可以使用自定义图例,但我需要在一个或两个点上方添加一个图标,并在图标悬停时显示一个弹出框。我需要从非图表相关数据构建弹出文本字符串。

自定义数据标签似乎不够灵活,无法在不同的数据点上显示不同的图标/弹出框,不过我可能是错的。

另一种可能性是chartjs-plugin-datalabels,但我不确定。

带有自定义图标的折线图

标签: chart.js

解决方案


如果您的图表(画布)是固定大小的,您可以通过添加一个dataset仅指定要在图表中显示的图标的附加项来轻松解决此问题。

{
  data: data2.map((v, i) => imageIndexes.includes(i) ? v + 1.2 : null),
  fill: false,
  pointStyle: icon,
  pointRadius: 22,
  pointHoverRadius: 22
}

给定数据数组data2和数组imageIndexes,可以使用 构建data图标。请注意,这些值(如果有的话)是从 in 中的相应值派生的,但略微增加以使图像出现在它们之上。datasetArray.mapdata2

data2.map((v, i) => imageIndexes.includes(i) ? v + 1.2 : null)

此外,您需要tooltips在图表内定义一个对象options以设置弹出窗口的样式并确保仅当鼠标悬停在图标上时才显示工具提示。

tooltips: {
  filter: tooltipItem => tooltipItem.datasetIndex == 2,
  titleFontSize: 16,
  titleAlign: 'center',
  callbacks: {
    title: (tooltipItem) => tooltipItem.length == 0 ? null : tooltipText,
    label: () => null
  }
},

请查看下面截取的可运行代码。

const labels = ['A', 'B', 'C', 'D', 'E', 'F'];
const alerts = ['B', 'D'];
const data1 = [0, 2, 1, 3, 2, 1];
const data2 = [1, 3, 3, 4, 3, 2];
const imageIndexes = [1, 3];
const tooltipText = 'Efficiency of Standard Curve\nnot opimal';

var icon = new Image();
icon.src = 'https://i.stack.imgur.com/YvlWY.png';

const chart = new Chart(document.getElementById("myChart"), {
  type: "line",
  data: {
    labels: labels,
    datasets: [{
        data: data1,
        fill: false,
        backgroundColor: 'blue',
        borderColor: 'blue',
        lineTension: 0,
        pointRadius: 5,
        pointHoverRadius: 5,
        pointBorderWidth: 3,
        pointHoverBorderWidth: 3,
        pointBorderColor: 'white',
        pointHoverBorderColor: 'white'
      },
      {
        data: data2,
        fill: false,
        showLine: false,
        backgroundColor: 'orange',
        pointRadius: 4,
        pointHoverRadius: 4
      },
      {
        data: data2.map((v, i) => imageIndexes.includes(i) ? v + 1.2 : null),
        fill: false,
        pointStyle: icon,
        pointRadius: 22,
        pointHoverRadius: 22
      }
    ]
  },
  options: {
    responsive: false,
    title: {
      display: false
    },
    legend: {
      display: false
    },
    tooltips: {
      filter: tooltipItem => tooltipItem.datasetIndex == 2,
      titleFontSize: 16,
      titleAlign: 'center',
      callbacks: {
        title: (tooltipItem) => tooltipItem.length == 0 ? null : tooltipText,
        label: () => null
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          min: 0,
          max: 6,
          stepSize: 1
        }
      }],
      xAxes: [{
        gridLines: {
          display: false
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" style="width: 500px; height: 200px"></canvas>


推荐阅读