箱型图-使用js实现:中位数用不同颜色展示

楼主
我是社区第1139764位番薯,欢迎点我头像关注我哦~

一、效果展示

 

原始的使用边框呈现的效果不佳,不能直观的看到中位数

使用JS只渲染中位数后效果如下:

二、实现原理

找到中位数的元素,使用js在加载结束后改变该元素的style

中位数元素:

document.querySelector("#Chart__Cells__A3__E26__1621493e-dae3-4188-a09d-804f3bd8d56c__index__0 > svg > g.clipSeriesGroup > g > g:nth-child(5) > g:nth-child(1) > line:nth-child(4)")

 

其中有几个变量 :

E26是单元格,

g > g:nth-child(5) 是列的序号,不过好像是倒叙的

g:nth-child(1) 这个应该是系列 我这边只有一个系列所以都是1,

line:nth-child(4)这个是中位数的元素这个不用管

 

找到中位数元素后,使用js渲染:主要就是遍历 Chart__Cells__A3开头的ID 然后找到 g.clipSeriesGroup 下的24列数据我这边只有24列 然后将中位数的样式改变。

可以按自己的需求修改这几块变量

 

 

// 封装一个函数,用于查找符合条件的 line 元素

function findTargetLine(container, index, callback) {

    setInterval(function () {

        // 找到包含 clipSeriesGroup 类的 g 元素

        const clipSeriesGroup = container.querySelector('g.clipSeriesGroup');

        if (!clipSeriesGroup) {

            console.log(`未找到 clipSeriesGroup 元素,容器 ID: ${container.id}`);

            callback(null);

            return;

        }

        var targetGSelector1 = 'g > g:nth-child(' + index + ') > g:nth-child(1)';

        const targetG = clipSeriesGroup.querySelector(targetGSelector1);

        if (!targetG) {

            console.log('未找到目标 g 元素');

            callback(null);

            return;

        }

 

        // 找到目标 line 元素

        const targetLine = targetG.querySelector('line:nth-child(4)');

        if (!targetLine) {

            console.log('未找到目标 line 元素');

            callback(null);

            return;

        }

 

        callback(targetLine);

    }, 500);

}

 

// 使用属性选择器找到所有以 Chart__Cells__A3__A26 开头的容器元素

const containers = document.querySelectorAll('[id^="Chart__Cells__A3_"]');

const allTargetLines = [];

 

// 循环处理每个容器

containers.forEach((container) => {

    for (let index = 24; index >= 1; index--) {

        // 调用函数查找目标元素

        findTargetLine(container, index, function (lineElement) {

            // 若找到元素,修改其样式

            if (lineElement) {

                lineElement.style.fill = "rgb(162, 160, 152)";

                lineElement.style.fillOpacity = "1";

                lineElement.style.stroke = "rgb(234, 68, 49)";

                lineElement.style.strokeOpacity = "1";

                lineElement.style.strokeWidth = "1";

                lineElement.style.filter = "none";

                lineElement.style.pointerEvents = "auto";

                allTargetLines.push(lineElement);

                if (allTargetLines.length > 1) {

                    const prevLine = allTargetLines[allTargetLines.length - 2];

                    const currentLine = allTargetLines[allTargetLines.length - 1];

                    connectLines(prevLine, currentLine);

                }

            }

        });

    }

});

 

    

分享扩散:

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

0回帖数 1关注人数 120浏览人数
最后回复于:昨天 09:45

返回顶部 返回列表