Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (3)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607/*REQUIREMENTS_BEGIN{ "chart_type": "Donut Chart", "chart_name": "donut_chart_icons_01", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 20], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": [], "supported_effects": ["shadow", "radius_corner", "stroke"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 半圆饼图实现 - 使用半圆饼图表示数据值function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备 ---------- // 提取数据和配置 const jsonData = data; const chartData = jsonData.data.data || []; const variables = jsonData.variables || {}; const dataColumns = chartUtils.schema.columns(jsonData);
const typography = jsonData.typography || { title: { font_family: "Arial", font_size: "18px", font_weight: "bold" }, label: { font_family: "Arial", font_size: "12px", font_weight: "normal" }, description: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } }; let colors = jsonData.colors || { text_color: "#333333", field: {}, other: { primary: "#4682B4" // 默认主色调 } };
// 提取字段名称 const xField = chartUtils.schema.columnField(dataColumns, 0); const yField = chartUtils.schema.columnField(dataColumns, 1); // Set dimensions and margins const width = variables.width; const height = variables.height; const margin = { top: 40, right: 40, bottom: 40, left: 40 }; const chartWidth = width - margin.left - margin.right; const chartHeight = height - margin.top - margin.bottom; // Create SVG const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", height) .attr("viewBox", `0 0 ${width} ${height}`) .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg"); // Calculate center point and max radius const centerX = width / 2; const centerY = height / 2; const maxRadius = Math.min(chartWidth, chartHeight) / 2; // Create a root group const g = svg.append("g") .attr("transform", `translate(${centerX}, ${centerY})`) .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); // 创建饼图生成器 const pie = d3.pie() .value(d => +d[yField]) .sort(null);
// 创建弧形生成器 const arc = d3.arc() .innerRadius(maxRadius*0.5) .outerRadius(maxRadius) .padAngle(0) .cornerRadius(5);
// 计算每个组的百分比 const total = d3.sum(chartData, d => +d[yField]); const dataWithPercentages = chartData.map(d => ({ ...d, percentage: (+d[yField] / total) * 100 })); const sectors = pie(dataWithPercentages);
// 存储图像位置信息,用于后续避免标签重叠 const imagePositions = [];
// 计算避免标签与图像重叠的位置 function calculateLabelPosition(d, iconCentroid, iconWidth, innerRadius, outerRadius, textWidth, textHeight) { // 计算扇区中心角度 const angle = (d.startAngle + d.endAngle) / 2; // 计算基础文本位置(在内圆和外圆之间) const labelRadius = (innerRadius + outerRadius) / 2; const x = Math.sin(angle) * labelRadius; const y = -Math.cos(angle) * labelRadius; // 计算文本边界框 const textBBox = { x: x - textWidth / 2, y: y - textHeight / 2, width: textWidth, height: textHeight }; // 计算图像边界框 const iconBBox = { x: iconCentroid[0] - iconWidth / 2, y: iconCentroid[1] - iconWidth / 2, width: iconWidth, height: iconWidth }; // 检查边界框是否重叠 // 计算重叠程度 let overlapX = 0; let overlapY = 0; // 计算X轴重叠 if (textBBox.x < iconBBox.x + iconBBox.width && iconBBox.x < textBBox.x + textBBox.width) { // 找出重叠部分的左边界和右边界 const leftOverlap = Math.max(textBBox.x, iconBBox.x); const rightOverlap = Math.min(textBBox.x + textBBox.width, iconBBox.x + iconBBox.width); overlapX = rightOverlap - leftOverlap; } // 计算Y轴重叠 if (textBBox.y < iconBBox.y + iconBBox.height && iconBBox.y < textBBox.y + textBBox.height) { // 找出重叠部分的上边界和下边界 const topOverlap = Math.max(textBBox.y, iconBBox.y); const bottomOverlap = Math.min(textBBox.y + textBBox.height, iconBBox.y + iconBBox.height); overlapY = bottomOverlap - topOverlap; } // 只有当X轴和Y轴都有重叠时,才算是真正的重叠 const overlap = overlapX > 0 && overlapY > 0; if (overlap) { // 计算重叠面积占文本面积的比例 const overlapArea = overlapX * overlapY; const textArea = textWidth * textHeight; const overlapRatio = overlapArea / textArea; // 确定最小安全距离,基于重叠比例和图像尺寸 const minSafeDistance = iconWidth/2 + 5; // 最小基础安全距离 // 根据重叠比例增加安全距离,重叠越大,距离越远 const additionalDistance = Math.max(30 * overlapRatio, 10); const safetyDistance = minSafeDistance + additionalDistance; // 计算当前标签中心到图像中心的距离 const currentDistance = Math.sqrt( Math.pow(x - iconCentroid[0], 2) + Math.pow(y - iconCentroid[1], 2) ); // 如果当前位置与图标重叠,尝试沿圆周寻找合适的位置 if (currentDistance < safetyDistance) { // 在当前角度的基础上,尝试在圆周方向上偏移 // 尝试不同的偏移角度,寻找最佳位置 const maxOffset = Math.PI / 4; // 最大偏移±45度 const steps = 16; // 增加尝试步数 let bestPosition = null; let bestDistance = -1; let bestOverlapRatio = Infinity; // 记录最小重叠比例 // 在扇区角度范围内,以步进方式尝试不同位置 const sectorWidth = d.endAngle - d.startAngle; // 使用扇区宽度或最大偏移值中较小的一个作为搜索范围 const searchRange = Math.max(Math.min(maxOffset, sectorWidth * 0.8), Math.PI / 12); const angularStep = searchRange / steps; // 同时尝试不同的半径 const radiusVariations = [ labelRadius * 0.8, // 向内收缩 labelRadius, // 原始半径 labelRadius * 1.1, // 稍微向外扩展 labelRadius * 1.2 // 更多向外扩展 ]; // 扩大搜索范围 for (let i = -steps; i <= steps; i++) { // 计算偏移角度 const offsetAngle = angle + i * angularStep; // 对每种半径变化尝试 for (const testRadius of radiusVariations) { // 计算新位置 const newX = Math.sin(offsetAngle) * testRadius; const newY = -Math.cos(offsetAngle) * testRadius; // 计算新文本边界框 const newTextBBox = { x: newX - textWidth / 2, y: newY - textHeight / 2, width: textWidth, height: textHeight }; // 计算与图标的距离 const dist = Math.sqrt( Math.pow(newX - iconCentroid[0], 2) + Math.pow(newY - iconCentroid[1], 2) ); // 检查新位置是否与图标重叠 let newOverlapX = 0; let newOverlapY = 0; if (newTextBBox.x < iconBBox.x + iconBBox.width && iconBBox.x < newTextBBox.x + newTextBBox.width) { const leftOverlap = Math.max(newTextBBox.x, iconBBox.x); const rightOverlap = Math.min(newTextBBox.x + newTextBBox.width, iconBBox.x + iconBBox.width); newOverlapX = rightOverlap - leftOverlap; } if (newTextBBox.y < iconBBox.y + iconBBox.height && iconBBox.y < newTextBBox.y + newTextBBox.height) { const topOverlap = Math.max(newTextBBox.y, iconBBox.y); const bottomOverlap = Math.min(newTextBBox.y + newTextBBox.height, iconBBox.y + iconBBox.height); newOverlapY = bottomOverlap - topOverlap; } const newOverlap = newOverlapX > 0 && newOverlapY > 0; if (!newOverlap) { // 如果没有重叠,计算这个位置相对于理想位置的距离偏移 // 理想位置是沿着原角度的中间半径 const idealX = Math.sin(angle) * labelRadius; const idealY = -Math.cos(angle) * labelRadius; const deviationFromIdeal = Math.sqrt( Math.pow(newX - idealX, 2) + Math.pow(newY - idealY, 2) ); // 如果是首次找到无重叠位置,或者这个位置比之前找到的更接近理想位置 if (bestPosition === null || deviationFromIdeal < bestDistance) { bestPosition = [newX, newY]; bestDistance = deviationFromIdeal; bestOverlapRatio = 0; } } else if (bestOverlapRatio > 0) { // 如果有重叠但比之前找到的重叠度更小 const overlapArea = newOverlapX * newOverlapY; const textArea = textWidth * textHeight; const overlapRatio = overlapArea / textArea; if (overlapRatio < bestOverlapRatio) { // 如果重叠程度更小,也许是个好选择 bestPosition = [newX, newY]; bestDistance = dist; bestOverlapRatio = overlapRatio; } } } } // 如果找到了更好的位置,返回它 if (bestPosition !== null) { return bestPosition; } // 如果没有找到合适的圆周位置,则尝试调整半径 // 根据角度所在象限决定向内还是向外移动 const extraDistance = safetyDistance - currentDistance; let adjustedRadius; if (angle >= 0 && angle < Math.PI) { // 右半边,向外移动 adjustedRadius = labelRadius + extraDistance + 10; // 额外10像素作为缓冲 } else { // 左半边,向内移动(如果内径足够大)或向外移动(如果内径太小) if (innerRadius > textWidth) { adjustedRadius = Math.max(innerRadius * 0.6, labelRadius - extraDistance - 10); } else { adjustedRadius = labelRadius + extraDistance + 10; } } return [ Math.sin(angle) * adjustedRadius, -Math.cos(angle) * adjustedRadius ]; } } return [x, y]; }
// 估算文本宽度和高度的函数 function estimateTextDimensions(text, fontSize) { return chartUtils.text.estimate(text, { fontSize }); } // 计算扇区最大可用宽度 function calculateSectorMaxWidth(d, radius) { // 计算扇区角度 const sectorAngle = d.endAngle - d.startAngle; // 在弧的中间位置计算最大宽度 // 弧长 = 角度 * 半径,取80%作为安全尺寸 return sectorAngle * radius * 0.8; } // 截断或调整文本以适应最大宽度 function fitTextToWidth(text, fontSize, maxWidth) { const dimensions = estimateTextDimensions(text, fontSize); if (dimensions.width <= maxWidth) { return { text, fontSize }; } // 如果文本太长,先尝试缩小字体 const minFontSize = 10; // 最小可接受的字体大小 if (fontSize > minFontSize) { const newFontSize = Math.max(minFontSize, fontSize * (maxWidth / dimensions.width)); const newDimensions = estimateTextDimensions(text, newFontSize); if (newDimensions.width <= maxWidth) { return { text, fontSize: newFontSize }; } } // 如果缩小字体后仍然超出,则截断文本 const charWidth = fontSize * 0.6; const maxChars = Math.floor(maxWidth / charWidth) - 2; // 减2留出省略号空间 if (maxChars < 3) { // 如果连3个字符都放不下 return { text: "...", fontSize }; } return { text: text.substring(0, maxChars) + "...", fontSize }; } for (let i = 0; i < sectors.length; i++) { const d = sectors[i]; // 绘制甜甜圈图的各个部分 const path = g.append("path") .attr("fill", colorResolver.field(d.data[xField], 0, { fallbackKey: "primary" }).value) .attr("stroke", "none") .attr("stroke-width", 2) .attr("d", arc(d));
const outerLength = (d.endAngle - d.startAngle) * maxRadius;
let iconWidth = Math.min(outerLength / 3, 150); let iconHeight = iconWidth; if (iconWidth > 20) { const iconArc = d3.arc() .innerRadius(maxRadius) .outerRadius(maxRadius);
// 创建剪切路径 const clipId = `clip-${i}`; const defs = g.append("defs"); const clipPath = defs.append("clipPath") .attr("id", clipId); // 确保剪切路径有正确的位置和尺寸 const [cx, cy] = iconArc.centroid(d); clipPath.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", iconWidth / 2);
// 添加白色背景圆 const circle = g.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", iconWidth / 2 + 3) .attr("fill", "white") .attr("stroke", colorResolver.field(d.data[xField], 0, { fallbackKey: "primary" }).value) .attr("stroke-width", 2);
// 使用剪切路径裁剪图片 const icon = g.append("image") .attr("xlink:href", jsonData.images.field[d.data[xField]]) .attr("clip-path", `url(#${clipId})`) .attr("x", cx - iconWidth / 2) .attr("y", cy - iconHeight / 2) .attr("width", iconWidth) .attr("height", iconHeight);
// 存储图像位置信息 imagePositions.push({ centroid: [cx, cy], width: iconWidth, height: iconHeight });
let displayTextCategory = d.data[xField]; let displayTextNumerical = d.data.percentage >= 2 ? `${chartUtils.format.percent(d.data.percentage).text} (${chartUtils.format.autoText(+d.data[yField])})` : ''; let categoryFontSize = 20; let numericalFontSize = 20; // 计算扇区的最大可用宽度 const maxAvailableWidth = calculateSectorMaxWidth(d, (maxRadius + maxRadius*0.5) / 2); // 调整类别文本和字体大小以适应扇区 const fittedCategory = fitTextToWidth(displayTextCategory, categoryFontSize, maxAvailableWidth); displayTextCategory = fittedCategory.text; categoryFontSize = fittedCategory.fontSize; // 调整数值文本和字体大小 const fittedNumerical = fitTextToWidth(displayTextNumerical, numericalFontSize, maxAvailableWidth); displayTextNumerical = fittedNumerical.text; numericalFontSize = fittedNumerical.fontSize; // 估算文本尺寸 const categoryDimensions = estimateTextDimensions(displayTextCategory, categoryFontSize); const numericalDimensions = estimateTextDimensions(displayTextNumerical, numericalFontSize); // 计算标签总高度(包括两行文本和间距) const labelHeight = categoryDimensions.height + numericalDimensions.height + 5; // 取两行文本中较宽的一个作为标签宽度 const labelWidth = Math.max(categoryDimensions.width, numericalDimensions.width); // 对于大图标,调整标签区域以避免重叠 const labelInnerRadius = maxRadius * 0.4; // 稍微向内收缩内半径 const labelOuterRadius = maxRadius * 1.1; // 稍微向外扩展外半径 // 计算避免与图像重叠的标签位置 const labelPosition = calculateLabelPosition( d, [cx, cy], iconWidth, labelInnerRadius, labelOuterRadius, labelWidth, labelHeight ); const textCategory = g.append("text") .attr("transform", `translate(${labelPosition})`) .attr("text-anchor", "middle") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.label.font_family) .style("font-size", categoryFontSize) .text(displayTextCategory);
const textNumerical = g.append("text") .attr("transform", `translate(0,20) translate(${labelPosition})`) .attr("text-anchor", "middle") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.label.font_family) .style("font-size", numericalFontSize) .text(displayTextNumerical); } else { iconWidth = 20; iconHeight = 20; const iconArc = d3.arc() .innerRadius(maxRadius+30) .outerRadius(maxRadius+30);
// 创建剪切路径 const clipId = `clip-${i}`; const defs = g.append("defs"); const clipPath = defs.append("clipPath") .attr("id", clipId); // 确保剪切路径有正确的位置和尺寸 const [cx, cy] = iconArc.centroid(d); clipPath.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", iconWidth / 2);
// 添加白色背景圆 const circle = g.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", iconWidth / 2 + 3) .attr("fill", "white") .attr("stroke", colorResolver.field(d.data[xField], 0, { fallbackKey: "primary" }).value) .attr("stroke-width", 2);
// 使用剪切路径裁剪图片 const icon = g.append("image") .attr("xlink:href", jsonData.images.field[d.data[xField]]) .attr("clip-path", `url(#${clipId})`) .attr("x", cx - iconWidth / 2) .attr("y", cy - iconHeight / 2) .attr("width", iconWidth) .attr("height", iconHeight); // 存储图像位置信息 imagePositions.push({ centroid: [cx, cy], width: iconWidth, height: iconHeight }); let displayTextCategory = d.data[xField]; let displayTextNumerical = `${chartUtils.format.percent(d.data.percentage).text} (${chartUtils.format.autoText(+d.data[yField])})`; let categoryFontSize = 20; let numericalFontSize = 20; // 计算扇区的最大可用宽度 const maxAvailableWidth = calculateSectorMaxWidth(d, maxRadius + 30); // 调整类别文本和字体大小以适应扇区 const fittedCategory = fitTextToWidth(displayTextCategory, categoryFontSize, maxAvailableWidth); displayTextCategory = fittedCategory.text; categoryFontSize = fittedCategory.fontSize; // 调整数值文本和字体大小 const fittedNumerical = fitTextToWidth(displayTextNumerical, numericalFontSize, maxAvailableWidth); displayTextNumerical = fittedNumerical.text; numericalFontSize = fittedNumerical.fontSize; // 估算文本尺寸 const categoryDimensions = estimateTextDimensions(displayTextCategory, categoryFontSize); const numericalDimensions = estimateTextDimensions(displayTextNumerical, numericalFontSize); // 计算标签总高度(包括两行文本和间距) const labelHeight = categoryDimensions.height + numericalDimensions.height + 5; // 取两行文本中较宽的一个作为标签宽度 const labelWidth = Math.max(categoryDimensions.width, numericalDimensions.width); // 对于小图标情况,使用更大的内外半径差,给标签更多空间 const labelInnerRadius = maxRadius + 10; // 向外偏移一点 const labelOuterRadius = maxRadius + 70; // 更大的外半径给更多空间 // 计算不重叠的标签位置 const labelPosition = calculateLabelPosition( d, [cx, cy], iconWidth, labelInnerRadius, labelOuterRadius, labelWidth, labelHeight ); const fillColor = colorResolver.field(d.data[xField], 0, { fallbackKey: "primary" }).value;
const textCategory = g.append("text") .attr("transform", `translate(${labelPosition})`) .attr("text-anchor", "middle") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.label.font_family) .style("font-size", categoryFontSize) .text(displayTextCategory);
const textNumerical = g.append("text") .attr("transform", `translate(0,20) translate(${labelPosition})`) .attr("text-anchor", "middle") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.label.font_family) .style("font-size", numericalFontSize) .text(displayTextNumerical); } }
// 加入label const label = g.append("text") .attr("transform", `translate(${centerX}, ${centerY})`) .attr("text-anchor", "middle") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .text(jsonData.title);
// 添加图例 - 放在图表上方 const legendGroup = svg.append("g") .attr("transform", `translate(0, -85)`); // 计算字段名宽度并添加间距 const titleWidth = xField.length * 10; const titleMargin = 15; let xs = [...new Set(chartData.map(d => d[xField]))];
const legendSize = chartUtils.legend.draw(legendGroup, xs, colors, { x: titleWidth + titleMargin, y: 0, fontSize: 14, fontWeight: "bold", align: "left", maxWidth: chartWidth - titleWidth - titleMargin, shape: "rect", });
// 添加字段名称 legendGroup.append("text") .attr("x", 0) .attr("y", legendSize.height / 2) .attr("dominant-baseline", "middle") .attr("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-size", "16px") .style("font-weight", "bold") .text(xField); // 将图例组向上移动 height/2, 并居中 legendGroup.attr("transform", `translate(${(chartWidth - legendSize.width - titleWidth - titleMargin) / 2}, ${-legendSize.height / 2 - 20})`); return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411/*REQUIREMENTS_BEGIN{ "chart_type": "Donut Chart", "chart_name": "donut_chart_icons_02", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 20], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": [], "supported_effects": ["shadow", "radius_corner", "stroke"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 半圆饼图实现 - 使用半圆饼图表示数据值function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备 ---------- // 提取数据和配置 const jsonData = data; const chartData = jsonData.data.data || []; const variables = jsonData.variables || {}; const dataColumns = chartUtils.schema.columns(jsonData);
const typography = jsonData.typography || { title: { font_family: "Arial", font_size: "18px", font_weight: "bold" }, label: { font_family: "Arial", font_size: "12px", font_weight: "normal" }, description: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } }; let colors = jsonData.colors || { text_color: "#333333", field: {}, other: { primary: "#4682B4" // 默认主色调 } };
// 提取字段名称 const xField = chartUtils.schema.columnField(dataColumns, 0); const yField = chartUtils.schema.columnField(dataColumns, 1); // Set dimensions and margins const width = variables.width; const height = variables.height; const margin = { top: 40, right: 40, bottom: 40, left: 40 }; const chartWidth = width - margin.left - margin.right; const chartHeight = height - margin.top - margin.bottom; // Create SVG const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", height) .attr("viewBox", `0 0 ${width} ${height}`) .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg"); // Calculate center point and max radius const centerX = width / 2; const centerY = height / 2 + 100; const maxRadius = Math.min(chartWidth, chartHeight) / 2; // Create a root group const g = svg.append("g") .attr("transform", `translate(${centerX}, ${centerY})`) .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); // 创建饼图生成器 const pie = d3.pie() .value(d => +d[yField]) .sort(null) .startAngle(0) // 设置起始角度为-90度 .endAngle(2*Math.PI) // 设置结束角度为90度
// 创建弧形生成器 const arc = d3.arc() .innerRadius(maxRadius*0.5) .outerRadius(maxRadius) .padAngle(0) .cornerRadius(5);
// 计算每个组的百分比 const total = d3.sum(chartData, d => +d[yField]); const dataWithPercentages = chartData.map(d => ({ ...d, percentage: (+d[yField] / total) * 100 })); const sectors = pie(dataWithPercentages);
// 存储图像位置信息,用于后续避免标签重叠 const imagePositions = [];
// 计算避免标签与图像重叠的位置 function calculateLabelPosition(d, iconCentroid, iconWidth, innerRadius, outerRadius, textWidth, textHeight, isLargeIcon) { // 计算扇区中心角度 const angle = (d.startAngle + d.endAngle) / 2; // 计算图标半径,添加额外边距 const iconRadius = iconWidth / 2 + 5; // 增加安全距离,确保标签和图标不重叠 const safetyDistance = isLargeIcon ? iconRadius + Math.max(textWidth, textHeight) / 1.5 : iconRadius * 2; // 根据扇区角度调整标签位置 let labelRadius;
// 根据扇区的角度位置采用不同的放置策略 if (angle >= 0 && angle <= Math.PI / 4) { // 右上角,标签放在外圈右侧 labelRadius = outerRadius + safetyDistance / 2.5; } else if (angle > Math.PI / 4 && angle <= 3 * Math.PI / 4) { // 上半部,标签放在较远的位置 labelRadius = outerRadius + safetyDistance / 2; } else if (angle > 3 * Math.PI / 4 && angle <= 5 * Math.PI / 4) { // 左半部,标签靠近内圈 labelRadius = Math.max(innerRadius - safetyDistance / 1.8, innerRadius * 0.4); } else if (angle > 5 * Math.PI / 4 && angle <= 7 * Math.PI / 4) { // 下半部,标签放在较远的位置 labelRadius = outerRadius + safetyDistance / 2; } else { // 右下角,标签放在外圈右侧 labelRadius = outerRadius + safetyDistance / 2.5; } // 基于角度和半径计算最终位置 const x = Math.sin(angle) * labelRadius; const y = -Math.cos(angle) * labelRadius; // 额外检查:检测是否与图标有重叠 const distance = Math.sqrt( Math.pow(x - iconCentroid[0], 2) + Math.pow(y - iconCentroid[1], 2) ); // 如果距离太近,再增加一些距离 if (distance < safetyDistance) { const extraFactor = 2.0; // 增加额外的安全系数 const extraDistance = (safetyDistance - distance) * extraFactor; // 根据角度决定向哪个方向移动更多 if ((angle >= 0 && angle <= Math.PI / 4) || (angle > 7 * Math.PI / 4 && angle <= 2 * Math.PI)) { // 右侧区域,向外移动 labelRadius += extraDistance; } else if (angle > Math.PI / 4 && angle <= 3 * Math.PI / 4) { // 上方区域,向上移动 labelRadius += extraDistance; } else if (angle > 3 * Math.PI / 4 && angle <= 5 * Math.PI / 4) { // 左侧区域,优先向内移动 if (innerRadius > textWidth * 1.2) { labelRadius = Math.max(innerRadius * 0.35, labelRadius - extraDistance); } else { labelRadius += extraDistance; } } else { // 下方区域,向下移动 labelRadius += extraDistance; } // 重新计算位置 return [ Math.sin(angle) * labelRadius, -Math.cos(angle) * labelRadius ]; } return [x, y]; }
// 估算文本宽度和高度的函数 function estimateTextDimensions(text, fontSize) { return chartUtils.text.estimate(text, { fontSize }); } // 计算扇区最大可用宽度 function calculateSectorMaxWidth(d, radius) { // 计算扇区角度 const sectorAngle = d.endAngle - d.startAngle; // 在弧的中间位置计算最大宽度 // 弧长 = 角度 * 半径,取80%作为安全尺寸 return sectorAngle * radius * 0.8; } // 调整文本以适应最大宽度 - 只缩小字体,不截断文本 function fitTextToWidth(text, fontSize, maxWidth) { const dimensions = estimateTextDimensions(text, fontSize); if (dimensions.width <= maxWidth) { return { text, fontSize }; } // 如果文本太长,尝试缩小字体 const minFontSize = 8; // 最小可接受的字体大小 if (fontSize > minFontSize) { const newFontSize = Math.max(minFontSize, fontSize * (maxWidth / dimensions.width)); return { text, fontSize: newFontSize }; } return { text, fontSize: minFontSize }; } // 计算标签位置 - 确保标签始终在外部,不会出现在饼图内部 function calculateOuterLabelPosition(d, outerRadius) { // 计算扇区中心角度 const angle = (d.startAngle + d.endAngle) / 2; // 确保标签始终在外圈,添加更大的边距确保不会出现在内部 // 增加倍数从1.2到1.5,确保标签彻底在外部 const labelRadius = outerRadius * 1.5; // 基于角度和半径计算最终位置 return [ Math.sin(angle) * labelRadius, -Math.cos(angle) * labelRadius ]; } // 检查扇区是否有足够空间放置图标 function hasEnoughSpaceForIcon(d, innerRadius) { // 计算扇区的内圆弧长度 const sectorAngle = d.endAngle - d.startAngle; const arcLength = sectorAngle * innerRadius; // 严格判断:扇区必须足够大才显示图标 // 最小要求提高到30像素,确保图标有足够空间 return arcLength >= 30; } for (let i = 0; i < sectors.length; i++) { const d = sectors[i]; // 绘制甜甜圈图的各个部分 const path = g.append("path") .attr("fill", colorResolver.field(d.data[xField], 0, { fallbackKey: "primary" }).value) .attr("stroke", "#FFFFFF") .attr("stroke-width", 2) .attr("d", arc(d));
// 检查扇区是否有足够空间放置图标 const innerRadius = maxRadius * 0.75; const hasSpace = hasEnoughSpaceForIcon(d, innerRadius); // 只有当扇区空间足够大时才显示图标 if (hasSpace) { // 计算扇区的内圆弧长度 const sectorAngle = d.endAngle - d.startAngle; const arcLength = sectorAngle * innerRadius; // 根据弧长计算图标大小,保持最小和最大限制 const minIconSize = 16; // 最小图标尺寸 const maxIconSize = 50; // 最大图标尺寸 const baseIconSize = Math.min(maxIconSize, Math.max(minIconSize, arcLength * 0.5)); // 设置图标尺寸 const iconWidth = baseIconSize; const iconHeight = baseIconSize; // 计算图标位置 - 确保图标在内圆弧上居中 const angle = (d.startAngle + d.endAngle) / 2; const iconRadius = innerRadius; // 确保图标位于内圆弧之上 const cx = Math.sin(angle) * iconRadius; const cy = -Math.cos(angle) * iconRadius; // 创建剪切路径 const clipId = `clip-${i}`; const defs = g.append("defs"); const clipPath = defs.append("clipPath") .attr("id", clipId); clipPath.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", iconWidth / 2);
// 添加白色背景圆 g.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", iconWidth / 2 + 3) .attr("fill", "white") .attr("stroke", colorResolver.field(d.data[xField], 0, { fallbackKey: "primary" }).value) .attr("stroke-width", 2);
// 使用剪切路径裁剪图片 g.append("image") .attr("xlink:href", jsonData.images.field[d.data[xField]]) .attr("clip-path", `url(#${clipId})`) .attr("x", cx - iconWidth / 2) .attr("y", cy - iconHeight / 2) .attr("width", iconWidth) .attr("height", iconHeight); } // 标签处理 - 所有标签都放在外部 // 准备显示的文本 let displayTextCategory = d.data[xField]; let displayTextValue = `${chartUtils.format.percent(d.data.percentage).text} (${chartUtils.format.autoText(+d.data[yField])})`; // 设置初始字体大小 let categoryFontSize = 14; let valueFontSize = 12; // 计算标签位置 - 确保标签在外部 const labelPosition = calculateOuterLabelPosition(d, maxRadius); // 计算最大可用宽度 - 外部标签可以有更多空间 const outerSpaceWidth = width * 0.4; // 增加到宽度的40% // 调整文本字体大小以确保文本完整显示 const fittedCategory = fitTextToWidth(displayTextCategory, categoryFontSize, outerSpaceWidth); const fittedValue = fitTextToWidth(displayTextValue, valueFontSize, outerSpaceWidth); // 设置文本颜色 const fillColor = colorResolver.field(d.data[xField], 0, { fallbackKey: "primary" }).value; // 计算文本颜色 - 使用黑色作为默认颜色,确保可读性 const textColor = "#000000"; // 添加标签 - 类别名称 g.append("text") .attr("transform", `translate(${labelPosition})`) .attr("text-anchor", "middle") .style("fill", textColor) .style("font-family", typography.label.font_family) .style("font-size", `${fittedCategory.fontSize}px`) .style("font-weight", "bold") .text(fittedCategory.text);
// 添加标签 - 百分比和原始值 g.append("text") .attr("transform", `translate(${labelPosition[0]}, ${labelPosition[1] + fittedCategory.fontSize + 4})`) .attr("text-anchor", "middle") .style("fill", textColor) .style("font-family", typography.label.font_family) .style("font-size", `${fittedValue.fontSize}px`) .text(fittedValue.text); // 添加辅助线连接扇区和标签 const arcCentroid = arc.centroid(d); // 连接线起点位于扇区中心位置 const lineStartX = arcCentroid[0]; const lineStartY = arcCentroid[1]; // 连接线终点位于标签起始位置的90%处,避免直接连到文字 const lineEndX = labelPosition[0] * 0.9; const lineEndY = labelPosition[1] * 0.9; g.append("line") .attr("x1", lineStartX) .attr("y1", lineStartY) .attr("x2", lineEndX) .attr("y2", lineEndY) .attr("stroke", "#888888") .attr("stroke-width", 1) .attr("stroke-dasharray", "3,3"); }
// 加入label const label = g.append("text") .attr("transform", `translate(${centerX}, ${centerY})`) .attr("text-anchor", "middle") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .text(jsonData.title);
// 添加图例 - 放在图表上方 const legendGroup = svg.append("g"); // 计算字段名宽度并添加间距 const titleWidth = xField.length * 10; const titleMargin = 15; let xs = [...new Set(chartData.map(d => d[xField]))];
const legendSize = chartUtils.legend.draw(legendGroup, xs, colors, { x: titleWidth + titleMargin, y: 0, fontSize: 14, fontWeight: "bold", align: "left", maxWidth: chartWidth - titleWidth - titleMargin, shape: "rect", });
// 添加字段名称 legendGroup.append("text") .attr("x", 0) .attr("y", legendSize.height / 2) .attr("dominant-baseline", "middle") .attr("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-size", "16px") .style("font-weight", "bold") .text(xField); // 将图例组向上移动 height/2, 并居中 legendGroup.attr("transform", `translate(${(chartWidth - legendSize.width - titleWidth - titleMargin) / 2}, ${-legendSize.height / 2 - 50})`); return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346/*REQUIREMENTS_BEGIN{ "chart_type": "Donut Chart", "chart_name": "donut_chart_icons_03", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 20], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": [], "supported_effects": ["shadow", "radius_corner", "stroke"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 半圆饼图实现 - 使用半圆饼图表示数据值function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备 ---------- // 提取数据和配置 const jsonData = data; const chartData = jsonData.data.data || []; const variables = jsonData.variables || {}; const dataColumns = chartUtils.schema.columns(jsonData);
const typography = jsonData.typography || { title: { font_family: "Arial", font_size: "18px", font_weight: "bold" }, label: { font_family: "Arial", font_size: "12px", font_weight: "normal" }, description: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } }; let colors = jsonData.colors || { text_color: "#333333", field: {}, other: { primary: "#4682B4" // 默认主色调 } };
// 提取字段名称 const xField = chartUtils.schema.columnField(dataColumns, 0); const yField = chartUtils.schema.columnField(dataColumns, 1); // Set dimensions and margins const width = variables.width; const height = variables.height; const margin = { top: 40, right: 40, bottom: 40, left: 40 }; const chartWidth = width - margin.left - margin.right; const chartHeight = height - margin.top - margin.bottom; // Create SVG const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", height) .attr("viewBox", `0 0 ${width} ${height}`) .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg"); // Calculate center point and max radius const centerX = width / 2; const centerY = height / 2; const maxRadius = Math.min(chartWidth, chartHeight) / 2; // Create a root group const g = svg.append("g") .attr("transform", `translate(${centerX}, ${centerY})`) .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); // 创建饼图生成器 const pie = d3.pie() .value(d => +d[yField]) .sort(null);
// 创建弧形生成器 const arc = d3.arc() .innerRadius(maxRadius*0.5) .outerRadius(maxRadius) .padAngle(0) .cornerRadius(5);
// 计算每个组的百分比 const total = d3.sum(chartData, d => +d[yField]); const dataWithPercentages = chartData.map(d => ({ ...d, percentage: (+d[yField] / total) * 100 })); const sectors = pie(dataWithPercentages);
// 计算标签位置的函数 function calculateLabelPosition(d, iconCentroid, iconWidth, innerRadius, outerRadius, textWidth, textHeight, isLargeIcon) { // 计算扇区中心角度 const angle = (d.startAngle + d.endAngle) / 2; // 计算图标半径,添加额外边距 const iconRadius = iconWidth / 2 + 5; // 增加安全距离,确保标签和图标不重叠 const safetyDistance = 20; // 所有标签都放在外圈,统一使用较大的半径 const labelRadius = outerRadius + safetyDistance; // 基于角度和半径计算最终位置 const x = Math.sin(angle) * labelRadius; const y = -Math.cos(angle) * labelRadius; // 额外检查:检测是否与图标有重叠 const distance = Math.sqrt( Math.pow(x - iconCentroid[0], 2) + Math.pow(y - iconCentroid[1], 2) ); // 如果距离太近,再增加一些距离 if (distance < safetyDistance) { const extraFactor = 1.5; // 增加额外的安全系数 const extraDistance = (safetyDistance - distance) * extraFactor; labelRadius += extraDistance; // 重新计算位置 return [ Math.sin(angle) * labelRadius, -Math.cos(angle) * labelRadius ]; } return [x, y]; }
// 估算文本宽度和高度的函数 function estimateTextDimensions(text, fontSize) { return chartUtils.text.estimate(text, { fontSize }); } // 计算扇区最大可用宽度 function calculateSectorMaxWidth(d, radius) { // 计算扇区角度 const sectorAngle = d.endAngle - d.startAngle; // 在弧的中间位置计算最大宽度 // 弧长 = 角度 * 半径,取80%作为安全尺寸 return Math.min(sectorAngle * radius * 0.8, 60); // 添加硬限制60 } // 截断或调整文本以适应最大宽度 function fitTextToWidth(text, fontSize, maxWidth) { const dimensions = estimateTextDimensions(text, fontSize); if (dimensions.width <= maxWidth) { return { text, fontSize }; } // 如果文本太长,先尝试缩小字体 const minFontSize = 10; // 最小可接受的字体大小 if (fontSize > minFontSize) { const newFontSize = Math.max(minFontSize, fontSize * (maxWidth / dimensions.width)); const newDimensions = estimateTextDimensions(text, newFontSize); if (newDimensions.width <= maxWidth) { return { text, fontSize: newFontSize }; } } // 如果缩小字体后仍然超出,则截断文本 const charWidth = fontSize * 0.6; const maxChars = Math.floor(maxWidth / charWidth) - 2; // 减2留出省略号空间 if (maxChars < 3) { // 如果连3个字符都放不下 return { text: "...", fontSize }; } return { text: text.substring(0, maxChars) + "...", fontSize }; } for (let i = 0; i < sectors.length; i++) { const d = sectors[i]; // 绘制甜甜圈图的各个部分 const path = g.append("path") .attr("fill", colorResolver.field(d.data[xField], 0, { fallbackKey: "primary" }).value) .attr("stroke", "#FFFFFF") .attr("stroke-width", 2) .attr("d", arc(d));
// 计算扇区中心点 // 创建一个专门用于计算扇区中心的弧生成器 const arcCentroid = d3.arc() .innerRadius((maxRadius*0.5 + maxRadius) / 2) // 使用内外半径的中点 .outerRadius((maxRadius*0.5 + maxRadius) / 2); // 获取扇区中心点坐标 const [cx, cy] = arcCentroid.centroid(d); // 计算图标尺寸,根据扇区大小调整 const angleSize = d.endAngle - d.startAngle; const iconSizeBase = Math.min(angleSize * maxRadius * 0.3, 60); let iconWidth = Math.max(iconSizeBase, 20); // 至少20像素 let iconHeight = iconWidth; // 创建剪切路径 const clipId = `clip-${i}`; const defs = g.append("defs"); const clipPath = defs.append("clipPath") .attr("id", clipId); // 设置剪切路径 clipPath.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", iconWidth / 2);
// 添加白色背景圆 const circle = g.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", iconWidth / 2 + 3) .attr("fill", "white") .attr("stroke", colorResolver.field(d.data[xField], 0, { fallbackKey: "primary" }).value) .attr("stroke-width", 2);
// 使用剪切路径裁剪图片 const icon = g.append("image") .attr("xlink:href", jsonData.images.field[d.data[xField]]) .attr("clip-path", `url(#${clipId})`) .attr("x", cx - iconWidth / 2) .attr("y", cy - iconHeight / 2) .attr("width", iconWidth) .attr("height", iconHeight);
// 计算标签位置(在外部) const labelPosition = calculateLabelPosition( d, [cx, cy], iconWidth, maxRadius*0.5, maxRadius, iconWidth, iconHeight, true ); // 准备显示文本 let displayTextCategory = d.data[xField]; let displayTextNumerical = chartUtils.format.percent(d.data.percentage).text; // 设置字体大小 let categoryFontSize = 20; let numericalFontSize = 20; // 估算文本尺寸 const categoryDimensions = estimateTextDimensions(displayTextCategory, categoryFontSize); const numericalDimensions = estimateTextDimensions(displayTextNumerical, numericalFontSize); // 计算标签总高度(包括两行文本和间距) const labelHeight = categoryDimensions.height + numericalDimensions.height + 5; // 取两行文本中较宽的一个作为标签宽度 const labelWidth = Math.max(categoryDimensions.width, numericalDimensions.width); // 根据角度决定文本对齐方式 const angle = (d.startAngle + d.endAngle) / 2; let textAnchor; if (angle < Math.PI/8 || angle > 15*Math.PI/8) { textAnchor = "middle"; // 正上方和正下方,居中对齐 } else if (angle >= Math.PI/8 && angle < 7*Math.PI/8) { textAnchor = "start"; // 右侧区域,左对齐 } else if (angle >= 7*Math.PI/8 && angle < 9*Math.PI/8) { textAnchor = "middle"; // 正左方,居中对齐 } else if (angle >= 9*Math.PI/8 && angle < 15*Math.PI/8) { textAnchor = "end"; // 左侧区域,右对齐 } else { textAnchor = "middle"; // 默认值 } // 确定文本颜色 const textColor = colorResolver.text({ fallback: "#333333" }).value; // 添加文本标签 // 添加类别文本 const textCategory = g.append("text") .attr("transform", `translate(${labelPosition})`) .attr("text-anchor", textAnchor) .style("fill", textColor) .style("font-family", typography.label.font_family) .style("font-size", `${categoryFontSize}px`) .text(displayTextCategory);
// 添加数值文本(在类别下方) const textNumerical = g.append("text") .attr("transform", `translate(0,20) translate(${labelPosition})`) .attr("text-anchor", textAnchor) .style("fill", textColor) .style("font-family", typography.label.font_family) .style("font-size", `${numericalFontSize}px`) .style("font-weight", "bold") .text(displayTextNumerical);
}
// 加入label const label = g.append("text") .attr("transform", `translate(${centerX}, ${centerY})`) .attr("text-anchor", "middle") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .text(jsonData.title);
// 添加图例 - 放在图表上方 const legendGroup = svg.append("g") .attr("transform", `translate(0, -50)`); // 计算字段名宽度并添加间距 const titleWidth = xField.length * 10; const titleMargin = 15; let xs = [...new Set(chartData.map(d => d[xField]))];
const legendSize = chartUtils.legend.draw(legendGroup, xs, colors, { x: titleWidth + titleMargin, y: 0, fontSize: 14, fontWeight: "bold", align: "left", maxWidth: chartWidth - titleWidth - titleMargin, shape: "rect", });
// 添加字段名称 legendGroup.append("text") .attr("x", 0) .attr("y", legendSize.height / 2) .attr("dominant-baseline", "middle") .attr("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-size", "16px") .style("font-weight", "bold") .text(xField); // 将图例组向上移动 height/2, 并居中 legendGroup.attr("transform", `translate(${(chartWidth - legendSize.width - titleWidth - titleMargin) / 2}, ${-legendSize.height / 2 - 20})`); return svg.node();}modules/chart_engine/template/d3-js/type49_donut_chart/donut_chart_icons_01.jsAdded+607
modules/chart_engine/template/d3-js/type49_donut_chart/donut_chart_icons_02.jsAdded+411
modules/chart_engine/template/d3-js/type49_donut_chart/donut_chart_icons_03.jsAdded+346