chart.js - ChartJs 折线图 - 在某些数据点上方显示永久图标,并在悬停时显示文本
问题描述
我有一个需要绘制的图表,除了数据点之外,我还想要一个带有自定义文本字符串的(某些)数据点上方永久的图标。
我不需要默认值弹出框,因为我可以使用自定义图例,但我需要在一个或两个点上方添加一个图标,并在图标悬停时显示一个弹出框。我需要从非图表相关数据构建弹出文本字符串。
自定义数据标签似乎不够灵活,无法在不同的数据点上显示不同的图标/弹出框,不过我可能是错的。
另一种可能性是chartjs-plugin-datalabels,但我不确定。
解决方案
如果您的图表(画布)是固定大小的,您可以通过添加一个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 中的相应值派生的,但略微增加以使图像出现在它们之上。dataset
Array.map
data2
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>
推荐阅读
- macos - 如果我没有配置 cron 作业,为什么 crontab 会运行我的脚本?
- rundeck - Rundeck 中的复选框选项
- python-3.x - 如何选择数据框中的一行,其中一个单元格值尽可能接近另一个预定义值
- java - 上传文件到谷歌云存储(JAVA)
- react-native - React Native TensorFlow 问题
- flutter - Flutter 自定义滑块
- sql - SQL Server:尝试更改表以添加外键约束时出错
- c# - C# 启动一个进程并在主模块加载后立即挂起
- prometheus - PromQL 查询之间的区别
- testing - TestCafe RequestLogger - 如何在对每个请求对象进行断言之前等待所有响应返回