ChartJS 2.9.4折线图按数值区间设置背景色及标注需求
ChartJS 2.9.4 折线图背景区间样式实现方案
实现说明
要实现指定的背景区间样式,需借助chartjs-plugin-annotation插件(与ChartJS 2.9.4兼容版本),通过该插件可添加背景色块、分隔虚线及右侧标注文字。先引入插件CDN,再在图表配置中添加对应注解项即可完成需求。
完整代码
<!-- 引入依赖资源 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.min.js"></script> <canvas id="lineChart"></canvas> <script> var ctx = document.getElementById("lineChart").getContext("2d"); var chart = new Chart(ctx, { type: "line", data: { labels: [ "", "Working Memory", "Inhibitory Control", "Cognitive Flexibility", "High Order EF", "", ], datasets: [ { label: "Competence score in Percent", data: [null, 80, 65, 90, 75], borderColor: "#000", backgroundColor: [ "#000", "#ffdb14", "#ff0000", "#38b7fe", "#8866f9", ], fill: false, pointRadius: 16, pointHoverRadius: 8, pointBackgroundColor: [ "#000", "#ffdb14", "#ff0000", "#38b7fe", "#8866f9", ], lineTension: 0, borderWidth: 2, }, ], }, options: { responsive: true, scales: { xAxes: [ { scaleLabel: { display: true, labelString: "Subtests", fontSize: 24, }, ticks: { fontSize: 24, }, }, ], yAxes: [ { scaleLabel: { display: true, labelString: "Competence score in Percent", fontSize: 24, }, ticks: { beginAtZero: true, min: 0, max: 100, stepSize: 25, fontSize: 24, }, }, ], }, legend: { display: false, }, // 配置区间注解 annotation: { annotations: [ // 60-80区间:浅灰背景+虚线+Significant标注 { type: "box", yScaleID: "y-axis-0", yMin: 60, yMax: 80, backgroundColor: "rgba(200,200,200,0.3)", borderWidth: 0 }, { type: "line", yScaleID: "y-axis-0", yMin: 60, yMax: 60, borderColor: "#999", borderWidth: 1, borderDash: [5,5], xMin: -0.5, xMax: chart.data.labels.length - 0.5 }, { type: "text", xScaleID: "x-axis-0", yScaleID: "y-axis-0", x: chart.data.labels.length - 0.2, y: 70, content: "Significant", fontSize: 16, fontColor: "#333", textAlign: "right" }, // 80-100区间:深灰背景+虚线+Severe标注 { type: "box", yScaleID: "y-axis-0", yMin: 80, yMax: 100, backgroundColor: "rgba(150,150,150,0.3)", borderWidth: 0 }, { type: "line", yScaleID: "y-axis-0", yMin: 80, yMax: 80, borderColor: "#666", borderWidth: 1, borderDash: [5,5], xMin: -0.5, xMax: chart.data.labels.length - 0.5 }, { type: "text", xScaleID: "x-axis-0", yScaleID: "y-axis-0", x: chart.data.labels.length - 0.2, y: 90, content: "Severe", fontSize: 16, fontColor: "#333", textAlign: "right" } ] } }, }); </script>
关键配置解释
box类型注解:用于绘制区间背景色块,通过yMin/yMax定义数值范围,backgroundColor设置半透明灰色实现背景效果line类型注解:绘制区间分隔虚线,borderDash参数定义虚线样式text类型注解:添加右侧标注文字,通过x/y定位到区间中间靠右的位置,确保标注与区间对应
内容的提问来源于stack exchange,提问作者Nitin Sharma
相关产品推荐
相关产品推荐

