ApexCharts如何绘制从标记点到X轴底部的十字准线
实现ApexCharts十字准线从数据点延伸至X轴底部
要实现十字准线仅从数据标记点延伸到X轴底部的效果,需要关闭默认的全局十字准线,通过图表的鼠标事件动态绘制自定义线条,具体实现如下:
关键修改逻辑
- 禁用x轴默认的贯穿式十字准线
- 监听图表鼠标移动/离开事件,动态添加或清除自定义垂直线
- 利用ApexCharts提供的坐标转换方法,精准定位数据点与X轴底部的坐标
修改后的完整代码
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> <div id="chart" class="apex-charts" dir="ltr"></div> <script> const data = [45, 52, 78, 45, 69, 23, 30, 45, 52, 88] const dataXCategories = ["10.12", "11.12", "12.12", "13.12", "14.12", "15.12", "16.12", "17.12", "18.12", "19.12"] const chartInstance = new ApexCharts(document.getElementById('chart'), { chart: { height: 165, type: "area", toolbar: { show: false }, events: { mouseMove: function(event, chartContext, config) { // 清除上一次的自定义十字准线 chartInstance.removeAnnotation('custom-crosshair'); if (config.dataPointIndex !== undefined) { // 获取当前数据点的Y值 const yValue = data[config.dataPointIndex]; // 将数据值转换为画布上的像素坐标 const pointY = chartInstance.toYCoordinate(yValue); const xAxisBottomY = chartInstance.toYCoordinate(0); const pointX = chartInstance.toXCoordinate(config.dataPointIndex); // 添加自定义垂直线注释 chartInstance.addAnnotation({ id: 'custom-crosshair', type: 'line', x: pointX, y: pointY, x2: pointX, y2: xAxisBottomY, stroke: { color: '#4A3AFF', width: 2, dashArray: 0 } }); } }, mouseLeave: function() { // 鼠标离开图表时清除十字准线 chartInstance.removeAnnotation('custom-crosshair'); } } }, stroke: { show: true, curve: 'smooth', lineCap: 'butt', colors: undefined, width: 2, dashArray: 0, }, colors: ["#00f"], dataLabels: { enabled: false }, series: [{ name: "Series 1", data: data }], fill: { type: "gradient", gradient: { shadeIntensity: 1, opacityFrom: .7, opacityTo: .9, stops: [0, 90, 100] } }, xaxis: { categories: dataXCategories, labels: { show: true, format: 'dd/MM', style: { fontSize: "11px", fontWeight: 400, fontFamily: "Inter", colors: ["#999", "#999", "#999", "#999", "#999", "#999", "#999", "#999", "#999", "#999"], } }, // 关闭默认的贯穿式十字准线 crosshairs: { show: false } }, yaxis: { min: 0, max: 100, tickAmount: 4, labels: { show: true, offsetX: -12, style: { fontSize: "11px", fontWeight: 400, fontFamily: "Inter", colors: ["#999"], }, formatter: function(value) { return `${value}%`; } }, }, grid: { show: true, borderColor: '#EDEDED', strokeDashArray: 0, position: 'back', xaxis: { lines: { show: true } }, yaxis: { lines: { show: true } }, row: { colors: undefined, opacity: .5 }, column: { colors: undefined, opacity: .5 }, padding: { top: 0, right: 0, bottom: 0, left: 0 }, }, markers: { colors: '#4A3AFF', hover: { size: undefined, sizeOffset: 7 } } }).render(); </script>
代码说明
- 禁用默认十字准线:将
xaxis.crosshairs.show设置为false,取消贯穿整个图表高度的默认垂直线 - 动态绘制自定义线条:在
mouseMove事件中,通过toYCoordinate/toXCoordinate将数据值转换为画布像素坐标,调用addAnnotation绘制从数据点到X轴底部的垂直线 - 清理残留线条:在
mouseLeave事件中移除自定义注释,确保鼠标离开后无残留线条
内容的提问来源于stack exchange,提问作者Dmitriy
相关产品推荐
相关产品推荐

