当前位置: 首页 > news >正文

d3.js绘制组合PCA边缘分布图

用d3.js研发了个组合PCA边缘分布图;

组合PCA边缘分布图中包括pca散点图、散点图可根据数据自动分为连续型和离散型、还有散点的各种配置、边缘有箱线边缘、密度边缘、柱状边缘一个各个边缘的配置等等,大部分你能想到的配置都是自行传参调整的,想不到的也能稍作修改然后自行调整,上代码:

import * as d3 from "d3";
import { dispersedColorList, gradientColorList } from "@/utils/commonData";const pcaCombinationEdgeChart = (options = {}) => {let originContainer = document.querySelector("#chart-container");let originHeight = originContainer.offsetHeight;let originWidth = originContainer.offsetWidth;let height = originHeight * (options.height / 100);let width = originWidth * (options.width / 100);// 获取标签样式function getSvgTextStyle({text = "",fontSize = 14,fontFamily = "Arial",fontWeight = "normal"} = {}) {const svg = d3.select("body").append("svg").attr("class", "get-svg-text-style");const textStyle = svg.append("text").text(text).attr("font-size", fontSize).attr("font-family", fontFamily).attr("font-weight", fontWeight).node().getBBox();svg.remove();return {width: textStyle.width,height: textStyle.height};}// 获取线性坐标轴宽高function getSvgLinearAxisStyle({fontSize = 20,orient = "bottom",fontFamily = "Arial",fontWeight = "normal",rotate = 0,domain = [0, 9],range = [0, 200]} = {}) {let axis;let svg = d3.select("body").append("svg").attr("width", 200).attr("height", 100).attr("transform", "translate(300, 200)").attr("class", "get-svg-axis-style");let scale = d3.scaleLinear().domain(domain).range(range);if (orient === "bottom" || orient === "top") {axis = d3.axisBottom(scale);} else {axis = d3.axisLeft(scale);}let axisStyle = svg.append("g").call(axis).call((g) => {g.selectAll("text").attr("fill", "#555").attr("font-size", fontSize).attr("font-family", fontFamily).attr("font-weight", fontWeight).attr("tmpY",g.select("text").attr("tmpY") || g.select("text").attr("dy")).attr("dy",rotate > 70 && rotate <= 90? "0.35em": rotate >= -90 && rotate < -70? "0.4em": g.select("text").attr("tmpY")).attr("text-anchor",orient === "left"? "end": rotate? rotate > 0? "start": "end": "middle").attr("transform",`translate(0, 0) ${rotate ? `rotate(${rotate} 0 ${g.select("text").attr("y")})` : ""}`);}).node().getBBox();svg.remove();return {width: axisStyle.width,height: axisStyle.height};}const symbolZoomTimes = 10;const symbolZoomTimesHover = 15;// 散点类型const symbolTypes = {circle: d3.symbolCircle,cross: d3.symbolCross,diamond: d3.symbolDiamond,square: d3.symbolSquare,star: d3.symbolStar,triangle: d3.symbolTriangle,wye: d3.symbolWye};// 线条样式const lineShapes = {point: "2 2",straigh_line: "0",dash_dot: "10 10 2 2",long_dash: "20 10 2 2",short_straight_line: "10 10"};// 选择器类名const classList = [".svg-groups-hull-group",".svg-groups-ellipse-group",".svg-groups-line-group",".svg-groups-scatter-group",".svg-groups-label-group"];// pca名称列表const pcaNameList = ["PC1", "PC2", "PC3"];const combinationBoxplot = {PC1: "pc1Boxplot",PC2: "pc2Boxplot",PC3: "pc3Boxplot"};const combinationAreas = {PC1: "pc1Areas",PC2: "pc2Areas",PC3: "pc3Areas"};const combinationBarplot = {PC1: "pc1BarData",PC2: "pc2BarData",PC3: "pc3BarData"};// 图例鼠标移入移出事件function legendMouse(type, index, data = []) {data.forEach((item, i) => {let opacity = type === "mouseout" ? 1 : index == i ? 1 : 0.3;let fontWeight =type === "mouseout" ? "normal" : index == i ? "bold" : "normal";d3.select(`.svg-legend-label-item${i}`).attr("font-weight", fontWeight);classList.forEach((subItem) => {d3.selectAll(subItem + i).attr("opacity", opacity);});});}// 图例图表点击事件function legendClick(index, color = "") {let el = d3.selectAll(`.svg-groups-scatter-group${index}`);let visibility = el.attr("visibility");let isVisibility = visibility? visibility === "visible"? true: false: true;d3.select(`.svg-legend-label-item${index}`).attr("fill",isVisibility ? "#ccc" : "#000");d3.select(`.svg-legend-path-item${index}`).attr("fill",isVisibility ? "#ccc" : color);classList.forEach((item) => {if (isVisibility) {el.attr("visibility", "hidden");} else {el.attr("visibility", "visible");}});}// tooltipfunction tooltip({group,sample,xValue,yValue,mate,left,top,parentElement}) {if (d3.select(".scatter-tooltip").empty()) {d3.select("body").append("div").attr("class", "scatter-tooltip").html(`<div class="scatter-tooltip-group">group: ${group}</div><div class="scatter-tooltip-sample">sample: ${sample}</div><div class="scatter-tooltip-x">X轴:${xValue}</div><div class="scatter-tooltip-y">Y轴:${yValue}</div>`).style("position", "fixed").style("left", `${left}px`).style("top", `${top}px`).style("padding", "8px 5px").style("border-radius", "4px").style("font-size", "12px").style("color", "#555").style("background", "rgba(255, 255,  255, .8)").style("border", `1px solid ${d3.select(parentElement).attr("fill")}`);} else {d3.select(".scatter-tooltip").style("display", "block").style("left", `${left}px`).style("top", `${top}px`).style("border", `1px solid ${d3.select(parentElement).attr("fill")}`);d3.select(".scatter-tooltip-group").html(`group: ${group}`);d3.select(".scatter-tooltip-sample").html(`sample: ${sample}`);d3.select(".scatter-tooltip-x").html(` X轴: ${xValue}`);d3.select(".scatter-tooltip-y").html(` Y轴: ${yValue}`);}}let {container = "#pca-container",left = 20,right = 350,bottom = 20,groupList = [],plot_type = "scatter", // 散点:scatter,按组连线:polygon,置信椭圆:ellipsedot_types = {SCL: "circle",CL: "circle",TL: "circle",ML: "circle"},mateDot_types = {Mate1: "circle",Mate2: "circle"},dot_size = 10,opacity = 0.4,grid_enabled = false,border_enabled = true,center_line_enabled = false,auxiliary_line_enabled = false,line_type = "straigh_line",x_axis_value = "PC1",y_axis_value = "PC2",showGroupObj = {SCL: 0,CL: 0,TL: 0,ML: 0},label_color = "#000",label_font = "Arial",label_size = 10,isLabel = true,dotColorType = "group",dotShapeType = "group",ischeckLabel = false,checkLabelPosition = "leftTop",main_title = "main_title",main_title_color = "#000",main_title_font = "Arial",main_title_size = 14,x_title = "x_title",x_title_color = "#000",x_title_font = "Arial",x_title_size = 14,x_text_color = "#000",x_text_font = "Arial",x_text_size = 12,x_text_rotate = 0,y_title = "y_title",y_title_color = "#000",y_title_font = "Arial",y_title_size = 14,y_text_color = "#000",y_text_font = "Arial",y_text_size = 12,legend_title = "group",legend_title_color = "#000",legend_title_size = 14,legend_title_font = "Arial",legend_text_color = "#000",legend_text_font = "Arial",legend_text_size = 14,legend_title2 = "shape",legend_title_color2 = "#000",legend_title_size2 = 14,legend_title_font2 = "Arial",legend_text_color2 = "#000",legend_text_font2 = "Arial",legend_text_size2 = 14,legend_size = 7,stress = false,stressValue = "",// 新增可调参数plotType = "barPlot",cloud_opacity = 0.5,isGroup = true,isEdge = false,edgeColor = "#FDC0C0"} = options;const checkLabel = options.data.checkLabel;// 箱线图相关定义和计算const boxPlotMarginTop = 20;const data = options.data;const boxPlotHeight =isEdge && !isGroup ? 70 : data.list?.length * (10 + 5) + boxPlotMarginTop;const allBoxplotHight = 30;const mTop = isEdge ? boxPlotHeight : 15;// 针对多边形和椭圆let forwardValue = `${x_axis_value}_${y_axis_value}`;let reverseValue = `${y_axis_value}_${x_axis_value}`;let colors = dispersedColorList[options.color];let colorListMates = dispersedColorList[options.colorMate];let colorListMateLiners = gradientColorList[options.colorMateLiner];// options.colorList.forEach((item) => {//   colors.push(item.color);// });// options.colorListMate.forEach((item) => {//   colorListMates.push(item.color);// });// options.colorListMateLiner.forEach((item) => {//   colorListMateLiners.push(item.color);// });let newGroupcheck = [];newGroupcheck = data.groups?.filter((item, index) => {if (groupList.indexOf(item.group) !== -1) {return item;}});let medianNum = (data.mateRange[0] + data.mateRange[1]) / 2;let data_tip = [data.mateRange[0], medianNum, data.mateRange[1]];let data_tip_backup = [];data_tip.map((item) => {data_tip_backup.push(Number(item).toFixed(2));});const colorScale = d3.scaleLinear().domain(data_tip_backup).range(colorListMateLiners);const box = document.querySelector(container);if (!box || !data.list || !data.list.length) return;if (data.type === "two") {data.list.forEach((item) => {let lineData = item.line[forwardValue] || item.line[reverseValue];lineData.ellipse = [];});}if (data.type === "one") {data.list.forEach((item) => {let lineData = item.line[forwardValue] || item.line[reverseValue];lineData.hull = [];});}let xIndex = pcaNameList.indexOf(x_axis_value);let yIndex = pcaNameList.indexOf(y_axis_value);let xCoordSet = [];let yCoordSet = [];data.list.forEach((item, index) => {xCoordSet.push(item.center[0][xIndex]);yCoordSet.push(item.center[0][yIndex]);item.data.forEach((subItem, j) => {xCoordSet.push(Number(subItem[xIndex + 1]));yCoordSet.push(Number(subItem[yIndex + 1]));});let isAxisReverse = !item.line[forwardValue];let pcaXIndex = isAxisReverse ? 1 : 0;let pcaYIndex = isAxisReverse ? 0 : 1;let pcaData = item.line[forwardValue] || item.line[reverseValue];pcaData?.hull?.forEach((subItem, j) => {xCoordSet.push(subItem[pcaXIndex]);yCoordSet.push(subItem[pcaYIndex]);});pcaData?.ellipse?.forEach((subItem, j) => {xCoordSet.push(subItem[pcaXIndex]);yCoordSet.push(subItem[pcaYIndex]);});});const xOldMin = Math.min(...xCoordSet);const xOldMax = Math.max(...xCoordSet);const yOldMin = Math.min(...yCoordSet);const yOldMax = Math.max(...yCoordSet);// x、y作用域const xTmpDomain = [xOldMin, xOldMax];const yTmpDomain = [yOldMin, yOldMax];const xTmpMin = xTmpDomain[0];const xTmpMax = xTmpDomain[1];const xStep = Math.abs(xTmpMax * 0.1);const xMin = xTmpMin - xStep >= 0 ? -xStep : xTmpMin - xStep;const xMax = xTmpMax + xStep > 0 ? xTmpMax + xStep : xStep;const yTmpMin = yTmpDomain[0];const yTmpMax = yTmpDomain[1];const yStep = Math.abs(yTmpMax * 0.1);const yMin = yTmpMin - yStep >= 0 ? -yStep : yTmpMin - yStep;const yMax = yTmpMax + yStep > 0 ? yTmpMax + yStep : yStep;const xDomain = [xMin, xMax];const yDomain = [yMin, yMax];// 主标题高度const titleSpace = 10;const titleH = getSvgTextStyle({text: main_title,fontSize: main_title_size,fontFamily: main_title_font}).height;const titleW = getSvgTextStyle({text: main_title,fontSize: main_title_size,fontFamily: main_title_font}).width;const titleTotalH = main_title ? titleH + titleSpace : 0;// X轴及标题高度const xTitleSpace = 10;const xTitleH = getSvgTextStyle({text: data.var ? x_title + `[${data.var[xIndex]}%]` : x_title,fontSize: x_title_size,fontFamily: x_title_font}).height;const xTitleTotalH = xTitleH + xTitleSpace;const xAxisH = getSvgLinearAxisStyle({fontSize: x_text_size,fontFamily: x_text_font,rotate: x_text_rotate,domain: xDomain}).height;// Y轴及标题高度const yTitleSpace = 10;const yTitleW = getSvgTextStyle({text: data.var ? y_title + `[${data.var[yIndex]}%]` : y_title,fontSize: y_title_size,fontFamily: y_title_font}).height;const yTitleTotalW = yTitleW + yTitleSpace;const yAxisW = getSvgLinearAxisStyle({fontSize: y_text_size,fontFamily: y_text_font,domain: yDomain,orient: "left"}).width;// 图例宽、高、间距等const legendList = [];data.list.map((item) => {legendList.push({label: item.group,...getSvgTextStyle({text: item.group,fontSize: legend_text_size,fontFamily: legend_text_font})});});const legendShapeList = [];if (data.mateRange) {data.mateRange?.map((item) => {legendShapeList.push({label: item,...getSvgTextStyle({text: item,fontSize: legend_text_size2,fontFamily: legend_text_font2})});});}const legendLabelSpace = 5;const legendBottomSpace = 8;const legendRightSpace = 10;const legendLeftSpace = 15;const legendLabelH = legendList.length? Math.max(legendList[0].height, legend_size * 2): 0;const legendLabelW = d3.max(legendList, (d) => d.width + 20) || 0;const legendEachH = legendLabelH + legendBottomSpace;const legendEachW =legendLabelW + legend_size * 2 + legendLabelSpace + legendRightSpace;const chartHeight =height - mTop - bottom - titleTotalH - xTitleTotalH - xAxisH;const legendStep =options.dotColorType === options.dotShapeType? Math.floor(chartHeight / legendEachH): Math.floor((chartHeight - 50) / 2 / legendEachH);const legendColumn = Math.ceil(legendList.length / legendStep);const legendTotalw = legendList.length ? legendColumn * legendEachW : 0;const chartWidth =width -left -right -yTitleTotalW -yAxisW -legendLeftSpace -legendTotalw;// x轴值映射const xScale = d3.scaleLinear().domain(xDomain).range([0, chartWidth]);// y轴值映射const yScale = d3.scaleLinear().domain(yDomain).range([chartHeight, 0]);// X轴const xAxis = d3.axisBottom(xScale).tickSizeOuter(border_enabled ? -chartHeight : 0);// Y轴const yAxis = d3.axisLeft(yScale).tickSizeOuter(border_enabled ? -chartWidth : 0);!d3.select(container).select("svg").empty() &&d3.select(container).select("svg").remove();// 创建svgconst svg = d3.select(container).append("svg").attr("width", width).attr("height", height).attr("id", "pca-svg-container");// 创建X轴svg.append("g").attr("class", "svg-x-axis").attr("transform",`translate(${left + yTitleTotalW + yAxisW}, ${height - bottom - xTitleTotalH - xAxisH})`).call(xAxis).call((g) => {g.selectAll("text").attr("fill", x_text_color).attr("font-size", x_text_size).attr("font-family", x_text_font).attr("tmpY",g.select("text").attr("tmpY") || g.select("text").attr("dy")).attr("dy",x_text_rotate > 70 && x_text_rotate <= 90? "0.35em": x_text_rotate >= -90 && x_text_rotate < -70? "0.4em": g.select("text").attr("tmpY")).attr("text-anchor",x_text_rotate ? (x_text_rotate > 0 ? "start" : "end") : "middle").attr("transform",`translate(0, 0) ${x_text_rotate? `rotate(${x_text_rotate} 0 ${g.select("text").attr("y")})`: ""}`);});// 创建Y轴svg.append("g").attr("class", "svg-y-axis").attr("transform",`translate(${left + yTitleTotalW + yAxisW}, ${mTop + titleTotalH})`).call(yAxis).call((g) => {g.selectAll("text").attr("fill", y_text_color).attr("font-size", y_text_size).attr("font-family", y_text_font);});// 主标题;svg.append("g").attr("class", "svg-main-title").append("text").text(main_title).attr("fill", main_title_color).attr("font-family", main_title_font).attr("font-size", main_title_size).attr("text-anchor", "middle").attr("dominant-baseline", "ideographic").attr("transform",`translate(${left + yTitleTotalW + yAxisW + chartWidth / 2}, ${main_title ? titleH : 0})`);//NMDS 主标题下面标识svg.append("g").attr("class", "theme-pca").append("text").text(stressValue).attr("x", left + yTitleTotalW + yAxisW + chartWidth / 2).attr("y", main_title ? titleH + 10 : 10).attr("text-anchor", "middle").attr("fill", "rgba(0, 0, 0, 0.6)").attr("font-size", 12).attr("visibility", stress ? "visible" : "hidden");// X轴标题svg.append("g").attr("class", "svg-x-title").append("text").text(data.var?.length > 0 ? x_title + ` [${data.var[xIndex]}%]` : x_title).attr("fill", x_title_color).attr("font-family", x_title_font).attr("font-size", x_title_size).attr("text-anchor", "middle").attr("dominant-baseline", "hanging").attr("transform",`translate(${left + yTitleTotalW + yAxisW + chartWidth / 2}, ${height - bottom - xTitleH})`);// Y轴标题svg.append("g").attr("class", "svg-y-title").append("text").text(data.var?.length > 0 ? y_title + ` [${data.var[yIndex]}%]` : y_title).attr("fill", y_title_color).attr("font-family", y_title_font).attr("font-size", y_title_size).attr("text-anchor", "middle").attr("dominant-baseline", "hanging").attr("transform",`translate(${left}, ${mTop + titleH + chartHeight / 2}) rotate(-90)`);// 图例const legendEl = svg.append("g").attr("cursor", "pointer").attr("class", "svg-legend").attr("transform",`translate(${isEdge? width - right - legendTotalw + boxPlotHeight + 15: width - right - legendTotalw + 10}, ${mTop + titleTotalH})`);if (!data.isMate) {legendEl.append("g").attr("class", "svg-legend-title").append("text").text(legend_title).attr("fill", legend_title_color).attr("font-family", legend_title_font).attr("font-size", legend_title_size).attr("text-anchor", "middle").attr("dominant-baseline", "ideographic").attr("transform", `translate(${15}, ${0})`);// 图例iconlegendEl.append("g").attr("class", "svg-legend-path").selectAll("path").data(legendList).enter().append("path").attr("index", (d, i) => i).attr("class", (d, i) => `svg-legend-path-item svg-legend-path-item${i}`).attr("fill", (d, i) => {if (dotColorType == "mate") {return colorListMates[i % colorListMates.length];} else {return colors[i % colors.length];}}).attr("d", (d, i) => {if (dotShapeType == "mate") {const symbolType = mateDot_types[d.label];const symbolGenerator = d3.symbol().type(symbolTypes[symbolType]).size(dot_size * symbolZoomTimes);return symbolGenerator();} else {let group = data.list[i].group;let type = dot_types[group] || "circle";let symbol = d3.symbol().type(symbolTypes[type]).size(legend_size * symbolZoomTimes);return symbol();}}).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +10})`;}).on("mouseover", function (e, d) {if (dotColorType == "group") {let index = d3.select(this).attr("index");legendMouse("mouseover", index, data.list);}}).on("mouseout", function (e, d) {if (dotColorType == "group") {let index = d3.select(this).attr("index");legendMouse("mouseout", index, data.list);}}).on("click", function (e, d) {if (dotColorType == "group") {let index = d3.select(this).attr("index");legendClick(index, colors[index]);}});// 图例标签legendEl.append("g").attr("class", "svg-legend-label").selectAll("text").data(legendList).enter().append("text").text((d) => d.label).attr("index", (d, i) => i).attr("fill", legend_text_color).attr("font-size", legend_text_size).attr("font-family", legend_text_font).attr("dominant-baseline", "central").attr("class",(d, i) => `svg-legend-label-item svg-legend-label-item${i}`).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size * 2 + legendLabelSpace + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +11})`;});} else {if (data.dataType == "discrete" && dotColorType == dotShapeType) {legendEl.append("g").attr("class", "svg-legend-title").append("text").text(legend_title).attr("fill", legend_title_color).attr("font-family", legend_title_font).attr("font-size", legend_title_size).attr("text-anchor", "middle").attr("dominant-baseline", "ideographic").attr("transform", `translate(${15}, ${0})`);// 图例iconlegendEl.append("g").attr("class", "svg-legend-path").selectAll("path").data(dotColorType == "mate" ? legendShapeList : legendList).enter().append("path").attr("index", (d, i) => i).attr("class",(d, i) => `svg-legend-path-item svg-legend-path-item${i}`).attr("fill", (d, i) => {if (dotColorType == "mate") {return colorListMates[i % colorListMates.length];} else {return colors[i % colors.length];}}).attr("d", (d, i) => {if (dotShapeType == "mate") {const symbolType = mateDot_types[d.label];const symbolGenerator = d3.symbol().type(symbolTypes[symbolType]).size(dot_size * symbolZoomTimes);return symbolGenerator();} else {let group = data.list[i].group;let type = dot_types[group] || "circle";let symbol = d3.symbol().type(symbolTypes[type]).size(legend_size * symbolZoomTimes);return symbol();}}).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +10})`;}).on("mouseover", function (e, d) {if (dotColorType == "group") {let index = d3.select(this).attr("index");legendMouse("mouseover", index, data.list);}}).on("mouseout", function (e, d) {if (dotColorType == "group") {let index = d3.select(this).attr("index");legendMouse("mouseout", index, data.list);}}).on("click", function (e, d) {if (dotColorType == "group") {let index = d3.select(this).attr("index");legendClick(index, colors[index]);}});// 图例标签legendEl.append("g").attr("class", "svg-legend-label").selectAll("text").data(dotColorType == "mate" ? legendShapeList : legendList).enter().append("text").text((d) => d.label).attr("index", (d, i) => i).attr("fill", legend_text_color).attr("font-size", legend_text_size).attr("font-family", legend_text_font).attr("dominant-baseline", "central").attr("class",(d, i) => `svg-legend-label-item svg-legend-label-item${i}`).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size * 2 + legendLabelSpace + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +11})`;});} else if (data.dataType == "liner") {legendEl.append("g").attr("class", "svg-legend-title").append("text").text(legend_title).attr("fill", legend_title_color).attr("font-family", legend_title_font).attr("font-size", legend_title_size).attr("text-anchor", "middle").attr("dominant-baseline", "ideographic").attr("transform", `translate(${15}, ${0})`);// 图例iconlegendEl.append("g").attr("class", "svg-legend-path").selectAll("path").data(legendList).enter().append("path").attr("index", (d, i) => i).attr("class",(d, i) => `svg-legend-path-item svg-legend-path-item${i}`).attr("fill", (d, i) => {return colors[i % colors.length];}).attr("d", (d, i) => {let group = data.list[i].group;let type = dot_types[group] || "circle";let symbol = d3.symbol().type(symbolTypes[type]).size(legend_size * symbolZoomTimes);return symbol();}).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +10})`;});// 图例标签legendEl.append("g").attr("class", "svg-legend-label").selectAll("text").data(legendList).enter().append("text").text((d) => d.label).attr("index", (d, i) => i).attr("fill", legend_text_color).attr("font-size", legend_text_size).attr("font-family", legend_text_font).attr("dominant-baseline", "central").attr("class",(d, i) => `svg-legend-label-item svg-legend-label-item${i}`).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size * 2 + legendLabelSpace + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +11})`;});if (dotColorType == "mate") {let legendElHidth = d3.select(".svg-legend").node().getBoundingClientRect().height;const legendLiner = svg.append("g").attr("class", "svg-legend-liner").attr("transform",`translate(${isEdge? width - right - legendTotalw + boxPlotHeight + 15: width - right - legendTotalw + 10}, ${mTop + titleTotalH + legendElHidth + 45})`);legendLiner.append("g").attr("class", "svg-legend-title-liner").append("text").text(legend_title2).attr("fill", legend_title_color2).attr("font-family", legend_title_font2).attr("font-size", legend_title_size2).attr("text-anchor", "middle").attr("dominant-baseline", "ideographic").attr("transform", `translate(${15}, ${0})`);const defs = legendLiner.append("defs");const linearGradient = defs.append("linearGradient").attr("id", "linearColor").attr("height", 80).attr("x1", "0%").attr("y1", "0%").attr("x2", "0%").attr("y2", "100%");linearGradient.append("stop").attr("offset", "0%").style("stop-color", colorListMateLiners[2]);linearGradient.append("stop").attr("offset", "50%").style("stop-color", colorListMateLiners[1]);linearGradient.append("stop").attr("offset", "100%").style("stop-color", colorListMateLiners[0]);legendLiner.append("rect").attr("x", 0).attr("y", 10).attr("width", 10).attr("height", 70).style("fill", "url(#" + linearGradient.attr("id") + ")");legendLiner.append("g").selectAll(".ledend_text").data(data_tip_backup).enter().append("text").attr("class", "legend-text").text((d) => {return d;}).attr("x", 15).attr("y", (_, i) => {if (i === 0) {return 80;} else if (i === 1) {return 50;} else {return 20;}}).attr("text-anchor", "start").attr("fill", "rgb(0, 0, 0)").attr("font-size", 12).attr("font-family", "Arial");}} else {legendEl.append("g").attr("class", "svg-legend-title").append("text").text(legend_title).attr("fill", legend_title_color).attr("font-family", legend_title_font).attr("font-size", legend_title_size).attr("text-anchor", "middle").attr("dominant-baseline", "ideographic").attr("transform", `translate(${15}, ${0})`);// 图例iconlegendEl.append("g").attr("class", "svg-legend-path").selectAll("path").data(dotColorType == "mate" ? legendShapeList : legendList).enter().append("path").attr("index", (d, i) => i).attr("class",(d, i) => `svg-legend-path-item svg-legend-path-item${i}`).attr("fill", (d, i) => {if (dotColorType == "mate") {return colorListMates[i % colorListMates.length];} else {return colors[i % colors.length];}}).attr("d", (d, i) => {let type = "circle";let symbol = d3.symbol().type(symbolTypes[type]).size(legend_size * symbolZoomTimes);return symbol();}).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +10})`;}).on("mouseover", function (e, d) {if (dotColorType == "group") {let index = d3.select(this).attr("index");legendMouse("mouseover", index, data.list);}}).on("mouseout", function (e, d) {if (dotColorType == "group") {let index = d3.select(this).attr("index");legendMouse("mouseout", index, data.list);}}).on("click", function (e, d) {if (dotColorType == "group") {let index = d3.select(this).attr("index");legendClick(index, colors[index]);}});// 图例标签legendEl.append("g").attr("class", "svg-legend-label").selectAll("text").data(dotColorType == "mate" ? legendShapeList : legendList).enter().append("text").text((d) => d.label).attr("index", (d, i) => i).attr("fill", legend_text_color).attr("font-size", legend_text_size).attr("font-family", legend_text_font).attr("dominant-baseline", "central").attr("class",(d, i) => `svg-legend-label-item svg-legend-label-item${i}`).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size * 2 + legendLabelSpace + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +11})`;});let legendElHidth = d3.select(".svg-legend").node().getBoundingClientRect().height;const legendShape = svg.append("g").attr("class", "svg-legend-shape").attr("transform",`translate(${isEdge? width - right - legendTotalw + boxPlotHeight + 15: width - right - legendTotalw + 10}, ${mTop + titleTotalH + legendElHidth + 45})`);legendShape.append("g").attr("class", "svg-legend-shape-title").append("text").text(legend_title2).attr("fill", legend_title_color2).attr("font-family", legend_title_font2).attr("font-size", legend_title_size2).attr("text-anchor", "middle").attr("dominant-baseline", "ideographic").attr("transform", `translate(${15}, ${0})`);legendShape.append("g").attr("class", "svg-legend-shape-label").selectAll("text").data(dotShapeType == "mate" ? legendShapeList : legendList).enter().append("text").text((d) => d.label).attr("index", (d, i) => i).attr("fill", legend_text_color2).attr("font-size", legend_text_size2).attr("font-family", legend_text_font2).attr("dominant-baseline", "central").attr("class",(d, i) => `svg-legend-label-item svg-legend-label-item${i}`).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size * 2 + legendLabelSpace + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +10})`;});legendShape.append("g").attr("class", "svg-legend-shape-path").selectAll("path").data(dotShapeType == "mate" ? legendShapeList : legendList).enter().append("path").attr("index", (d, i) => i).attr("class",(d, i) => `svg-legend-path-item svg-legend-path-item${i}`).attr("fill", "rgb(0, 0, 0)").attr("d", (d, i) => {if (dotShapeType == "mate") {const shapeType = d.label.trim();const symbolType = mateDot_types[shapeType];const symbolGenerator = d3.symbol().type(symbolTypes[symbolType]).size(dot_size * symbolZoomTimes);return symbolGenerator();} else {let group = data.list[i].group;let type = dot_types[group] || "circle";let symbol = d3.symbol().type(symbolTypes[type]).size(legend_size * symbolZoomTimes);return symbol();}}).attr("transform", (d, i) => {let times = Math.floor(i / legendStep);return `translate(${legend_size + legendEachW * times}, ${legendLabelH / 2 +(legendLabelH + legendBottomSpace) * (i % legendStep) +10})`;});}}if (grid_enabled) {// 网格线Y轴d3.selectAll(".svg-x-axis .tick").append("line").attr("x1", 0).attr("y1", 0).attr("x2", 0).attr("y2", -chartHeight).attr("stroke-width", 1).attr("stroke", "rgba(0, 0, 0, 0.2)").style("stroke-dasharray", "5 5");d3.selectAll(".svg-y-axis .tick").append("line").attr("x1", 0).attr("y1", 0).attr("x2", chartWidth).attr("y2", 0).attr("stroke-width", 1).attr("stroke", "rgba(0, 0, 0, 0.2)").style("stroke-dasharray", "5 5");}// 原点辅助线if (auxiliary_line_enabled) {const auxiliaryEl = svg.append("g").attr("class", "svg-zero-line").attr("transform",`translate(${left + yTitleTotalW + yAxisW}, ${mTop + titleTotalH})`);auxiliaryEl.append("line").attr("class", "svg-zero-line-x").attr("x1", xScale(0) + 0.5).attr("y1", chartHeight).attr("x2", xScale(0) + 0.5).attr("y2", 0).attr("stroke", "rgba(0, 0, 0, 0.4)");auxiliaryEl.append("line").attr("class", "svg-zero-line-y").attr("x1", 0).attr("y1", yScale(0) + 0.5).attr("x2", chartWidth).attr("y2", yScale(0) + 0.5).attr("stroke", "rgba(0, 0, 0, 0.4)");}// 绘图区const groups = svg.append("g").attr("class", "svg-groups").attr("transform",`translate(${left + yTitleTotalW + yAxisW}, ${mTop + titleTotalH})`);if (ischeckLabel) {if (checkLabel) {const label = groups.append("text").text(checkLabel).attr("fill", "black").attr("font-size", 10);// 检验标签位置if (checkLabelPosition === "leftTop") {label.attr("x", 5).attr("y", 20).attr("text-anchor", "start");} else {label.attr("x", chartWidth - 5).attr("y", chartHeight - 10).attr("text-anchor", "end");}}}// 多边形(按组连线)if (dotColorType == "group" && plot_type === "polygon") {groups.append("g").attr("class", "svg-groups-hull").selectAll(".svg-groups-hull-group").data(data.list).enter().append("g").attr("fill-opacity", opacity).attr("fill", (d, i) => colors[i % colors.length]).attr("class",(d, i) => `svg-groups-hull-group svg-groups-hull-group${i}`).append("polygon").attr("stroke-width", 1).attr("stroke", (d, i) => colors[i % colors.length]).attr("stroke-dasharray", lineShapes[line_type]).attr("points", (d, i) => {let points = "";let data = (d.line[forwardValue] || d.line[reverseValue]).hull;let isAxisReverse = !d.line[forwardValue];let pcaXIndex = isAxisReverse ? 1 : 0;let pcaYIndex = isAxisReverse ? 0 : 1;data.forEach((item) => {points += `${xScale(item[pcaXIndex])}, ${yScale(item[pcaYIndex])} `;});return points;});}// 椭圆if (dotColorType == "group" && plot_type === "ellipse") {groups.append("g").attr("class", "svg-groups-ellipse").selectAll(".svg-groups-ellipse-group").data(data.list).enter().append("g").attr("fill-opacity", opacity).attr("fill", (d, i) => colors[i % colors.length]).attr("class",(d, i) => `svg-groups-ellipse-group svg-groups-ellipse-group${i}`).append("polygon").attr("stroke-width", 1).attr("stroke", (d, i) => colors[i % colors.length]).attr("stroke-dasharray", lineShapes[line_type]).attr("points", (d, i) => {let points = "";let isAxisReverse = !d.line[forwardValue];let pcaXIndex = isAxisReverse ? 1 : 0;let pcaYIndex = isAxisReverse ? 0 : 1;let data = (d.line[forwardValue] || d.line[reverseValue]).ellipse;data.forEach((item) => {points += `${xScale(item[pcaXIndex])}, ${yScale(item[pcaYIndex])} `;});return points;});}// 中心点连线if (center_line_enabled) {groups.append("g").attr("class", "svg-groups-line").selectAll(".svg-groups-line-group").data(data.list).enter().append("g").attr("index", (d, i) => i).attr("stroke-opacity", 0.3).attr("stroke", (d, i) => colors[i % colors.length]).attr("class",(d, i) => `svg-groups-line-group svg-groups-line-group${i}`).selectAll("line").data((d, i) => d.data).enter().append("line").attr("x1", (d, i, elList) => {let index = d3.select(elList[i].parentElement).attr("index");let centroids = data.list[index].center[0];return xScale(centroids[xIndex]);}).attr("y1", (d, i, elList) => {let index = d3.select(elList[i].parentElement).attr("index");let centroids = data.list[index].center[0];return yScale(centroids[yIndex]);}).attr("x2", (d) => xScale(d[xIndex + 1])).attr("y2", (d) => yScale(d[yIndex + 1]));}let uniqueMates = [];data.list.forEach((d) => {d.data.forEach((item) => {const mate = item[item.length - 1].trim();uniqueMates.push(mate);});});uniqueMates = [...new Set(uniqueMates)];let mateColorMap = uniqueMates.reduce((acc, mate, index) => {if (index < colorListMates.length) {acc[mate] = colorListMates[index];}return acc;}, {});// 散点if (dotColorType == "mate") {groups.append("g").attr("class", "svg-groups-scatter").selectAll(".svg-groups-scatter-group").data(data.list).enter().append("g").attr("index", (d, i) => i).attr("class", (d, i) => {return `svg-groups-common svg-groups-scatter-group svg-groups-scatter-group${i}`;}).selectAll("path").data((d) => d.data).enter().append("path").attr("d", (d, i, elList) => {if (data.dataType == "discrete" && dotShapeType == "mate") {const shapeType = d[d.length - 1].trim();const symbolType = mateDot_types[shapeType];const symbolGenerator = d3.symbol().type(symbolTypes[symbolType]).size(dot_size * symbolZoomTimes);return symbolGenerator();} else {let index = d3.select(elList[i].parentElement).attr("index");let group = data.list[index].group;let type = dot_types[group] || "circle";let symbol = d3.symbol().type(symbolTypes[type]).size(dot_size * symbolZoomTimes);return symbol();}}).attr("transform",(d, i) =>`translate(${xScale(d[xIndex + 1])}, ${yScale(d[yIndex + 1])})`).attr("fill", (d, i) => {if (data.dataType == "liner" && dotColorType == "mate") {return colorScale(d[d.length - 1]);} else if (dotColorType == "mate") {return mateColorMap[d[d.length - 1]];}}).on("mouseover", function (e, d) {let index = d3.select(this.parentElement).attr("index");if (data.isMate) {tooltip({group: data.list[index].group,sample: d[0],xValue: d[xIndex + 1],yValue: d[yIndex + 1],mate: d[xIndex + 4],left: e.pageX + 15,top: e.pageY - 27,parentElement: this.parentElement});} else {tooltip({group: data.list[index].group,sample: d[0],xValue: d[xIndex + 1],yValue: d[yIndex + 1],left: e.pageX + 15,top: e.pageY - 27,parentElement: this.parentElement});}}).on("mouseout", function (d, i, elList) {d3.select(".scatter-tooltip").style("display", "none");});} else {groups.append("g").attr("class", "svg-groups-scatter").selectAll(".svg-groups-scatter-group").data(data.list).enter().append("g").attr("index", (d, i) => i).attr("fill", (d, i) => {return colors[i % colors.length];}).attr("class",(d, i) =>`svg-groups-common svg-groups-scatter-group svg-groups-scatter-group${i}`).selectAll("path").data((d) => d.data).enter().append("path").attr("d", (d, i, elList) => {if (data.dataType == "discrete" && dotShapeType == "mate") {const shapeType = d[d.length - 1].trim();const symbolType = mateDot_types[shapeType];const symbolGenerator = d3.symbol().type(symbolTypes[symbolType]).size(dot_size * symbolZoomTimes);return symbolGenerator();} else {let index = d3.select(elList[i].parentElement).attr("index");let group = data.list[index].group;let type = dot_types[group] || "circle";let symbol = d3.symbol().type(symbolTypes[type]).size(dot_size * symbolZoomTimes);return symbol();}}).attr("transform",(d, i) =>`translate(${xScale(d[xIndex + 1])}, ${yScale(d[yIndex + 1])})`).on("mouseover", function (e, d) {let index = d3.select(this.parentElement).attr("index");if (data.isMate) {tooltip({group: data.list[index].group,sample: d[0],xValue: d[xIndex + 1],yValue: d[yIndex + 1],mate: d[xIndex + 4],left: e.pageX + 15,top: e.pageY - 27,parentElement: this.parentElement});} else {tooltip({group: data.list[index].group,sample: d[0],xValue: d[xIndex + 1],yValue: d[yIndex + 1],left: e.pageX + 15,top: e.pageY - 27,parentElement: this.parentElement});}}).on("mouseout", function (d, i, elList) {d3.select(".scatter-tooltip").style("display", "none");});}if (isLabel) {groups.append("g").attr("class", "svg-groups-label").selectAll(".svg-groups-label-group").data(data.list).enter().append("g").attr("class",(d, i) => `svg-groups-label-group svg-groups-label-group${i}`).selectAll("text").data((d) => {return d.data;}).enter().append("text").text((d) => d[0]).attr("text-anchor", "middle").attr("fill", label_color).attr("font-size", label_size).attr("font-family", label_font).attr("x", (d) => xScale(d[xIndex + 1])).attr("y", (d) => yScale(d[yIndex + 1]) - dot_size);}if (isEdge) {// 边缘箱线图// 获取svg-x-axis、svg-y-axis元素的宽度和高度let svgXaxisWidth = d3.select(".svg-x-axis").node().getBoundingClientRect().width;let svgXaxisHeigth = d3.select(".svg-x-axis").node().getBoundingClientRect().height;let svgYaxisWidth = d3.select(".svg-y-axis").node().getBoundingClientRect().width;let svgYaxisHeight = d3.select(".svg-y-axis").node().getBoundingClientRect().height;if (dotColorType !== "mate" && isGroup) {if (plotType === "boxplot") {const topBoxplots = svg.append("g").attr("class", "top-boxplot").attr("transform", `translate(${left + yTitleTotalW + yAxisW}, 0)`);topBoxplots.selectAll("rect").data(data.list).enter().append("rect").attr("transform", `translate(0, ${titleTotalH + boxPlotMarginTop})`).attr("y", (item, index) => index * (10 + 5)) //10表示箱体宽度 5表示每个箱体之间的间距.attr("height", 10).attr("width", (item) => {const val =xScale(item[combinationBoxplot[x_axis_value]][3]) -xScale(item[combinationBoxplot[x_axis_value]][1]);return val;}).attr("x", (item) =>xScale(item[combinationBoxplot[x_axis_value]][1])).attr("stroke-width", 1).attr("stroke", (d, i) => colors[i % colors.length]).attr("fill", (d, i) => colors[i % colors.length]).attr("fill-opacity", cloud_opacity);// 绘制中心线(中位数线)topBoxplots.selectAll("line.median").data(data.list).enter().append("line").classed("median", true).attr("transform", `translate(0, ${titleTotalH + boxPlotMarginTop})`).attr("y1", (item, index) => index * (10 + 5)).attr("y2", (item, index) => index * (10 + 5) + 10).attr("x1", (item) =>xScale(item[combinationBoxplot[x_axis_value]][2])).attr("x2", (item) =>xScale(item[combinationBoxplot[x_axis_value]][2])).attr("stroke", "black");// 绘制左须线topBoxplots.selectAll("line.whisker-left").data(data.list).enter().append("line").classed("whisker-left", true).attr("transform", `translate(0, ${titleTotalH + boxPlotMarginTop})`).attr("y1", (item, index) => index * (10 + 5) + 5).attr("y2", (item, index) => index * (10 + 5) + 5).attr("x1", (item) =>xScale(item[combinationBoxplot[x_axis_value]][0])) // 左须线从最小值开始.attr("x2", (item) =>xScale(item[combinationBoxplot[x_axis_value]][1])).attr("stroke", "black");// 绘制右须线topBoxplots.selectAll("line.whisker-right").data(data.list).enter().append("line").classed("whisker-right", true).attr("transform", `translate(0, ${titleTotalH + boxPlotMarginTop})`).attr("y1", (item, index) => index * (10 + 5) + 5).attr("y2", (item, index) => index * (10 + 5) + 5).attr("x1", (item) =>xScale(item[combinationBoxplot[x_axis_value]][3])) // 右须线从Q3开始,.attr("x2", (item) =>xScale(item[combinationBoxplot[x_axis_value]][4])) // 右须线到最大值.attr("stroke", "black");//右侧箱线图const rightBoxplots = svg.append("g").attr("class", "right-boxplot").attr("transform",`translate(${left + yTitleTotalW + yAxisW + svgXaxisWidth + 7}, ${titleH ? titleH + boxPlotHeight + 10 : titleH + boxPlotHeight})`);rightBoxplots.selectAll("rect").data(data.list).enter().append("rect").attr("transform", `translate(0, ${0})`).attr("x", (item, index) => index * (10 + 5)).attr("width", 10).attr("height", (item) => {const val =yScale(item[combinationBoxplot[y_axis_value]][1]) -yScale(item[combinationBoxplot[y_axis_value]][3]);return val;}).attr("y", (item) =>yScale(item[combinationBoxplot[y_axis_value]][3])).attr("stroke-width", 1).attr("stroke", (d, i) => colors[i % colors.length]).attr("fill", (d, i) => colors[i % colors.length]).attr("fill-opacity", cloud_opacity);// 绘制中心线(中位数线)rightBoxplots.selectAll("line.median").data(data.list).enter().append("line").classed("median", true).attr("x1", (item, index) => index * (10 + 5)).attr("x2", (item, index) => index * (10 + 5) + 10).attr("y1", (item) =>yScale(item[combinationBoxplot[y_axis_value]][2])).attr("y2", (item) =>yScale(item[combinationBoxplot[y_axis_value]][2])).attr("stroke", "black");// 绘制上须线rightBoxplots.selectAll("line.whisker-top").data(data.list).enter().append("line").classed("whisker-top", true).attr("x1", (item, index) => index * (10 + 5) + 5).attr("x2", (item, index) => index * (10 + 5) + 5).attr("y1", (item) =>yScale(item[combinationBoxplot[y_axis_value]][4])).attr("y2", (item) =>yScale(item[combinationBoxplot[y_axis_value]][3])).attr("stroke", "black");// 绘制下须线rightBoxplots.selectAll("line.whisker-bottom").data(data.list).enter().append("line").classed("whisker-bottom", true).attr("x1", (item, index) => index * (10 + 5) + 5).attr("x2", (item, index) => index * (10 + 5) + 5).attr("y1", (item) =>yScale(item[combinationBoxplot[y_axis_value]][0])).attr("y2", (item) =>yScale(item[combinationBoxplot[y_axis_value]][1])).attr("stroke", "black");}if (plotType === "areas") {const areaPlotsGroup = svg.append("g").attr("class", "areas-boxplot");// 为每个数据项创建一个g元素const areaPlots = areaPlotsGroup.selectAll(".area-plot").data(data.list).enter().append("g").attr("class", "area-plot").attr("transform", (item) => {return `translate(${left + yTitleTotalW + yAxisW},${titleH ? boxPlotHeight + titleH + 10 : boxPlotHeight})`;});const dScale = (topAreas) => {return d3.scaleLinear().domain([d3.min(topAreas, (d) => d.offset),d3.max(topAreas, (d) => d.offset)]).range([0, -boxPlotHeight + boxPlotMarginTop]);};const area = (d, topAreas) => {return d3.area().y0((d) => {return dScale(topAreas)(d.offset);}).x((d) => {return xScale(d.value);}).y1(0);};// 绘制面积密度图areaPlots.append("path").attr("fill", (d, i) => colors[i % colors.length]).attr("fill-opacity", cloud_opacity).attr("d", (item) =>area(null,item[combinationAreas[x_axis_value]])(item[combinationAreas[x_axis_value]]));// 添加垂直面积图的g元素const verticalAreaPlotsGroup = svg.append("g").attr("class", "vertical-areas-boxplot");// 为每个数据项创建一个g元素(垂直面积图)const verticalAreaPlots = verticalAreaPlotsGroup.selectAll(".vertical-area-plot").data(data.list).enter().append("g").attr("class", "vertical-area-plot").attr("transform", (item) => {return `translate(${left + yTitleTotalW + svgYaxisWidth},${titleH ? boxPlotHeight + titleH + 10 : boxPlotHeight})`;});// 定义垂直方向的缩放比例尺;const dVScale = (rightAreas) => {return d3.scaleLinear().domain([d3.min(rightAreas, (d) => d.offset),d3.max(rightAreas, (d) => d.offset)]).range([0, boxPlotHeight]);};const areaV = (d, rightAreas) => {return d3.area().x0((d) => {return dVScale(rightAreas)(d.offset);}).y((d) => {return yScale(d.value);}).x1(0);};// 绘制垂直方向的面积图verticalAreaPlots.append("path").attr("fill", (d, i) => colors[i % colors.length]).attr("fill-opacity", cloud_opacity).attr("d", (item) => {return areaV(null,item[combinationAreas[y_axis_value]])(item[combinationAreas[y_axis_value]]);});}if (plotType === "barPlot") {const numColumns =data.list[0][combinationBarplot[x_axis_value]].length;const topColumnWidth = (xDomain[1] - xDomain[0]) / numColumns;const rightColumnWidth = (yDomain[1] - yDomain[0]) / numColumns;const groupDataToPlot = {};data.list.forEach((item) => {groupDataToPlot[item.group] = item[combinationBarplot[x_axis_value]];});// 生成新的数据格式 上边缘const topData = Array.from({ length: numColumns }, (_, i) => {const x = xDomain[0] + i * topColumnWidth + topColumnWidth / 2; // 计算x坐标(柱子的中心)const plotData = {};// 遍历所有组,并将值添加到plotDatafor (const group of Object.keys(groupDataToPlot)) {plotData[group] = groupDataToPlot[group][i];}return { x, ...plotData };});const groupRDataToPlot = {};data.list.forEach((item) => {groupRDataToPlot[item.group] = item[combinationBarplot[x_axis_value]];});// 右 新数据const rightData = Array.from({ length: numColumns }, (_, i) => {const y = yDomain[0] + i * rightColumnWidth + rightColumnWidth / 2;const plotData = {};for (const group of Object.keys(groupRDataToPlot)) {plotData[group] = groupRDataToPlot[group][i];}return { y, ...plotData };});const keys = Object.keys(groupDataToPlot);const stackedData = d3.stack().keys(keys)(topData);const stackedData2 = d3.stack().keys(keys)(rightData);// 设置X轴和Y轴比例尺const topBarxScale = d3.scaleBand().domain(topData.map((d) => d.x)).range([0, svgXaxisWidth - 6]).padding(0.1);const topBaryScale = d3.scaleLinear().domain([0, d3.max(stackedData, (d) => d3.max(d, (d) => d[1]))]).range([boxPlotHeight - 10, 0]);const topBarPlotSvg = svg.append("g").attr("class", "bar-plot").attr("transform", (item) => {return `translate(${left + yTitleTotalW + yAxisW},${titleH ? titleH + 20 : titleH + 10})`;});// 绘制上边缘堆叠柱状图topBarPlotSvg.selectAll(".layer").data(stackedData).enter().append("g").attr("class", "layer").attr("fill", (d, i) => colors[i % colors.length]).attr("fill-opacity", cloud_opacity).selectAll("rect").data((d) => d).enter().append("rect").attr("x", (d) => topBarxScale(d.data.x)).attr("y", (d) => topBaryScale(d[1])).attr("height", (d) => topBaryScale(d[0]) - topBaryScale(d[1])).attr("width", topBarxScale.bandwidth());// 定义y轴(垂直方向),使用scaleBandconst rightBaryScale = d3.scaleBand().domain(rightData.map((d) => d.y)).range([svgYaxisHeight, 0]).padding(0.1);// 定义x轴(水平方向),使用scaleLinearconst rightBarxScale = d3.scaleLinear().domain([0, d3.max(stackedData2, (d) => d3.max(d, (e) => e[1]))]).range([0, boxPlotHeight]);const rightBarPlotSvg = svg.append("g").attr("class", "right-bar-plot").attr("transform", (item) => {return `translate(${left + yTitleTotalW + svgYaxisWidth},${titleH ? titleH + boxPlotHeight + 10 : titleH + boxPlotHeight})`;});// 绘制右边缘水平堆叠柱状图rightBarPlotSvg.selectAll(".layer").data(stackedData2).enter().append("g").attr("class", "layer").attr("fill", (d, i) => colors[i % colors.length]).attr("fill-opacity", cloud_opacity).selectAll("rect").data((d) => d).enter().append("rect").attr("y", (d) => {return rightBaryScale(d.data.y);}).attr("x", (d) => rightBarxScale(d[0])).attr("width", (d) => {return rightBarxScale(d[1]) - rightBarxScale(d[0]);}).attr("height", rightBaryScale.bandwidth());}} else {if (plotType === "boxplot") {const topBoxplotsAll = svg.append("g").attr("class", "top-boxplot-all").attr("transform", `translate(${left + yTitleTotalW + yAxisW}, -10)`);topBoxplotsAll.selectAll("rect").data(data.ALL[combinationBoxplot[x_axis_value]]).enter().append("rect").attr("transform", `translate(0, ${titleTotalH + boxPlotMarginTop})`).attr("y", 0).attr("height", allBoxplotHight).attr("width",xScale(data.ALL[combinationBoxplot[x_axis_value]][3]) -xScale(data.ALL[combinationBoxplot[x_axis_value]][1])).attr("x", xScale(data.ALL[combinationBoxplot[x_axis_value]][1])).attr("stroke-width", 1).attr("stroke", "rgba(0,0,0,0.5)").attr("fill", edgeColor).attr("fill-opacity", cloud_opacity);// 绘制中心线(中位数线)topBoxplotsAll.selectAll("line.median").data(data.ALL[combinationBoxplot[x_axis_value]]).enter().append("line").classed("median", true).attr("transform", `translate(0, ${titleTotalH + boxPlotMarginTop})`).attr("y1", 0).attr("y2", allBoxplotHight).attr("x1", xScale(data.ALL[combinationBoxplot[x_axis_value]][2])).attr("x2", xScale(data.ALL[combinationBoxplot[x_axis_value]][2])).attr("stroke", "black");// 绘制左须线topBoxplotsAll.selectAll("line.whisker-left").data(data.ALL[combinationBoxplot[x_axis_value]]).enter().append("line").classed("whisker-left", true).attr("transform", `translate(0, ${titleTotalH + boxPlotMarginTop})`).attr("y1", allBoxplotHight / 2).attr("y2", allBoxplotHight / 2).attr("x1", xScale(data.ALL[combinationBoxplot[x_axis_value]][0])).attr("x2", xScale(data.ALL[combinationBoxplot[x_axis_value]][1])).attr("stroke", "black");// 绘制右须线topBoxplotsAll.selectAll("line.whisker-right").data(data.ALL[combinationBoxplot[x_axis_value]]).enter().append("line").classed("whisker-right", true).attr("transform", `translate(0, ${titleTotalH + boxPlotMarginTop})`).attr("y1", allBoxplotHight / 2).attr("y2", allBoxplotHight / 2).attr("x1", xScale(data.ALL[combinationBoxplot[x_axis_value]][3])).attr("x2", xScale(data.ALL[combinationBoxplot[x_axis_value]][4])).attr("stroke", "black");//右侧箱线图const rightBoxplotsAll = svg.append("g").attr("class", "right-boxplot-all").attr("transform",`translate(${left + yTitleTotalW + yAxisW + svgXaxisWidth + 20}, ${titleH ? titleH + boxPlotHeight + 10 : titleH + boxPlotHeight})`);rightBoxplotsAll.selectAll("rect").data(data.ALL[combinationBoxplot[y_axis_value]]).enter().append("rect").attr("x", 0).attr("width", allBoxplotHight).attr("height",yScale(data.ALL[combinationBoxplot[y_axis_value]][1]) -yScale(data.ALL[combinationBoxplot[y_axis_value]][3])).attr("y", yScale(data.ALL[combinationBoxplot[y_axis_value]][3])).attr("stroke-width", 1).attr("stroke", "rgba(0,0,0,0.5)").attr("fill", edgeColor).attr("fill-opacity", cloud_opacity);// 绘制中心线(中位数线)rightBoxplotsAll.selectAll("line.median").data(data.ALL[combinationBoxplot[y_axis_value]]).enter().append("line").classed("median", true).attr("x1", 0).attr("x2", allBoxplotHight).attr("y1", yScale(data.ALL[combinationBoxplot[y_axis_value]][2])).attr("y2", yScale(data.ALL[combinationBoxplot[y_axis_value]][2])).attr("stroke", "black");// 绘制上须线rightBoxplotsAll.selectAll("line.whisker-top").data(data.ALL[combinationBoxplot[y_axis_value]]).enter().append("line").classed("whisker-top", true).attr("x1", allBoxplotHight / 2).attr("x2", allBoxplotHight / 2).attr("y1", yScale(data.ALL[combinationBoxplot[y_axis_value]][4])).attr("y2", yScale(data.ALL[combinationBoxplot[y_axis_value]][3])).attr("stroke", "black");// 绘制下须线rightBoxplotsAll.selectAll("line.whisker-bottom").data(data.ALL[combinationBoxplot[y_axis_value]]).enter().append("line").classed("whisker-bottom", true).attr("x1", allBoxplotHight / 2).attr("x2", allBoxplotHight / 2).attr("y1", yScale(data.ALL[combinationBoxplot[y_axis_value]][0])).attr("y2", yScale(data.ALL[combinationBoxplot[y_axis_value]][1])).attr("stroke", "black");}if (plotType === "areas") {let topAreas = data.ALL[combinationAreas[x_axis_value]];let rightAreas = data.ALL[combinationAreas[y_axis_value]];// 创建比例尺实例const dScaleAll = d3.scaleLinear().domain([d3.min(topAreas, (d) => d.offset),d3.max(topAreas, (d) => d.offset)]).range([0, -boxPlotHeight + boxPlotMarginTop]);// 创建面积生成器const areaGenerator = d3.area().y1(0).x((d) => xScale(d.value)).y0((d) => dScaleAll(d.offset));// 创建面积图组const areaPlotsGroupAll = svg.append("g").attr("class", "areas-all");// 为每个topArea创建一个g元素和路径const areaPlotsAll = areaPlotsGroupAll.selectAll(".area-plot-all").data([topAreas]).enter().append("g").attr("class", "area-plot-all").attr("transform",`translate(${left + yTitleTotalW + yAxisW + 2},${titleH ? boxPlotHeight + titleH + 7 : boxPlotHeight + titleH})`);// 绘制路径areaPlotsAll.append("path").datum(topAreas).attr("fill", edgeColor).attr("fill-opacity", cloud_opacity).attr("d", areaGenerator);//垂直!const dScaleAllV = d3.scaleLinear().domain([d3.min(rightAreas, (d) => d.offset),d3.max(rightAreas, (d) => d.offset)]).range([0, boxPlotHeight]);const areaGeneratorV = d3.area().x0((d) => dScaleAllV(d.offset)).y((d) => yScale(d.value)).x1(0);// 创建面积图组const areaPlotsGroupAllV = svg.append("g").attr("class", "areas-all-v");const areaPlotsAllV = areaPlotsGroupAllV.selectAll(".area-plot-all-v").data([rightAreas]).enter().append("g").attr("class", "area-plot-all-v").attr("transform",`translate(${left + yTitleTotalW + yAxisW + svgXaxisWidth},${titleH ? boxPlotHeight + titleH + 8 : boxPlotHeight + titleH})`);// 绘制路径areaPlotsAllV.append("path").datum(rightAreas).attr("fill", edgeColor).attr("fill-opacity", cloud_opacity).attr("d", areaGeneratorV);}if (plotType === "barPlot") {// 设置X轴和Y轴比例尺const topBarxScaleAll = d3.scaleBand().domain(d3.range(data.ALL[combinationBarplot[x_axis_value]].length)).range([0, svgXaxisWidth]).padding(0.1);const topBaryScaleAll = d3.scaleLinear().domain([0, d3.max(data.ALL[combinationBarplot[x_axis_value]])]).range([boxPlotHeight - 10, 0]);const topBarPlotSvgAll = svg.append("g").attr("class", "bar-plot-all").attr("transform",`translate(${left + yTitleTotalW + yAxisW},${titleH ? titleH + 8 : titleH - 2})`);topBarPlotSvgAll.selectAll(".bar").data(data.ALL[combinationBarplot[x_axis_value]]).enter().append("rect").attr("class", "bar").attr("x", (d, i) => topBarxScaleAll(i)).attr("width", topBarxScaleAll.bandwidth()).attr("y", (d) => topBaryScaleAll(d)).attr("height", (d) => boxPlotHeight - topBaryScaleAll(d)).attr("fill", edgeColor).attr("fill-opacity", cloud_opacity);// 设置水平X轴和Y轴比例尺const topBaryScaleAllV = d3.scaleBand().domain(d3.range(data.ALL[combinationBarplot[y_axis_value]].length)).range([0, svgYaxisHeight]).padding(0.1);const topBarxScaleAllV = d3.scaleLinear().domain([0, d3.max(data.ALL[combinationBarplot[y_axis_value]])]).range([boxPlotHeight, 0]);const topBarPlotSvgAllV = svg.append("g").attr("class", "bar-plot-all-v").attr("transform", (item) => {return `translate(${left + yTitleTotalW + yAxisW + svgXaxisWidth},${titleH ? titleH + boxPlotHeight + 10 : titleH + boxPlotHeight})`;});// 绘制水平柱状图topBarPlotSvgAllV.selectAll(".bar").data(data.ALL[combinationBarplot[y_axis_value]]).enter().append("rect").attr("class", "bar").attr("y", (d, i) => {return topBaryScaleAllV(i);}).attr("height", topBaryScaleAllV.bandwidth()).attr("x", 2).attr("width", (d) => {return topBarxScaleAllV(0) - topBarxScaleAllV(d);}).attr("fill", edgeColor).attr("fill-opacity", cloud_opacity);}}}
};export default pcaCombinationEdgeChart;

 页面调用:

 pcaCombinationEdgeChart({ data: plots, ...chartParam });

小小的展示一下部分效果吧

 

大概是去年年底研发完成的吧 实在是太多了太绕了阿!
有什么不懂的就自己研究吧,我反正是写完就忘了

相关文章:

  • 数据结构(6)
  • MYOJ_11700(UVA10591)Happy Number(快乐数)(超快解法:图论思想解题)
  • 阿尔特拉 EP1C12F324I7N AlteraFPGA Cyclone
  • Redis——数据结构
  • 【ELF2学习板】OpenCL程序测试
  • 逻辑删除表结构如何加唯一索引?
  • Obsidian的简单使用
  • 【Semantic Kernel核心组件】Kernel:掌控AI编排的“中央处理器“
  • Java基础知识面试题(已整理Java面试宝典pdf版)
  • AbMole—如何高效诱导巨噬细胞的极化?
  • 04-libVLC的视频播放器:获取媒体信息
  • 《手环表带保养全攻略:材质、清洁与化学品避坑指南》
  • 力扣349 == 两个数组交集的两种解法
  • 第十五届蓝桥杯青少Python省赛中级组真题 ——浇花系统
  • Java命名规则
  • 01、单片机简介
  • photo-sphere-viewer 4.8.1在vue中使用
  • Vim使用完全指南:从基础到高效编辑
  • 了解高速设计的信号完整性仿真
  • 计算机视觉算法实战——基于YOLOv8的农田智能虫情测报灯害虫种类识别系统开发指南
  • 郑培凯:汤显祖的“至情”与罗汝芳的“赤子之心”
  • 董军同法国国防部长举行会谈
  • 新闻1+1丨婚姻登记服务,如何跑出幸福加速度?
  • 香港暂停进口美国北达科他州一地区禽肉及禽类产品
  • 被流量绑架人生,《人生开门红》能戳破网络时代的幻象吗
  • 高培勇:中国资本市场的发展应将预期因素全面纳入分析和监测体系