Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (4)
- modules/chart_engine/template/d3-js/type71_small_multiples_of_gauge/small_multiples_gauge_plain_chart_01.jsAdded+240
- modules/chart_engine/template/d3-js/type71_small_multiples_of_gauge/small_multiples_gauge_plain_chart_02.jsAdded+329
- modules/chart_engine/template/d3-js/type71_small_multiples_of_gauge/small_multiples_gauge_plain_chart_03.jsAdded+333
- modules/chart_engine/template/d3-js/type71_small_multiples_of_gauge/small_multiples_gauge_plain_chart_04.jsAdded+548
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240/*REQUIREMENTS_BEGIN{ "chart_type": "Small Multiples of Gauge Chart", "chart_name": "small_multiples_gauge_plain_chart_01", "required_fields": ["x", "y", "group"], "required_fields_type": [["categorical"], ["numerical"], ["categorical"]], "required_fields_range": [[2, 9], [0, "inf"], [2, 3]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": ["group"], "required_other_colors": [], "supported_effects": [], "min_height": 400, "min_width": 600, "background": "light", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { // 数值格式化函数 // 提取数据 const jsonData = data; const chartData = jsonData.data.data; const variables = jsonData.variables; const typography = jsonData.typography; const colors = jsonData.colors || {}; const colorResolver = chartUtils.color.resolver(jsonData); const dataColumns = chartUtils.schema.columns(jsonData); const images = jsonData.images || {}; // 清空容器 d3.select(containerSelector).html(""); // 获取字段名 const xField = chartUtils.schema.columnField(dataColumns, 0); const yField = chartUtils.schema.columnField(dataColumns, 1); const groupField = chartUtils.schema.columnField(dataColumns, 2); // 设置尺寸和边距 const width = variables.width; const height = variables.height; const margin = { top: 60, right: 20, bottom: 20, left: 20 }; const chartWidth = width - margin.left - margin.right; const chartHeight = height - margin.top - margin.bottom; // 获取唯一的x值和group值 const uniqueXValues = [...new Set(chartData.map(d => d[xField]))]; const uniqueGroups = [...new Set(chartData.map(d => d[groupField]))]; // 计算每个group的全局总值,用于确定统一的排序顺序 const groupTotals = {}; uniqueGroups.forEach(group => { groupTotals[group] = chartData .filter(d => d[groupField] === group) .reduce((sum, d) => sum + (+d[yField]), 0); }); // 按全局总值从大到小排序group,确保所有子图顺序一致 const sortedGroups = uniqueGroups.sort((a, b) => groupTotals[b] - groupTotals[a]); const colorScale = colorResolver.scale(sortedGroups, { palette: "category10" }); // 按x分组数据 const groupedData = {}; uniqueXValues.forEach(xValue => { groupedData[xValue] = []; sortedGroups.forEach(group => { const item = chartData.find(d => d[xField] === xValue && d[groupField] === group); if (item) { groupedData[xValue].push({ group: group, value: +item[yField], color: colorScale(group) }); } }); // 移除单独排序,使用统一的sortedGroups顺序 }); // 计算全局最大值,确保所有子图刻度一致 const globalMaxValue = Math.max(...chartData.map(d => +d[yField])); const angleScale = d3.scaleLinear().domain([0, globalMaxValue]).range([0, Math.PI]); // 创建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") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); chartUtils.legend.centered(svg, sortedGroups, { colorScale, colorResolver, colors, }, width / 2, 15, { markerShape: "circle", markerSize: 10, labelGap: 5, itemGap: 15, fontSize: 12, textColor: colorResolver.text({ fallback: "#333" }).value, }); // 优化网格布局逻辑 const numCharts = uniqueXValues.length; let rows, cols; if (numCharts === 2) { rows = 1; cols = 2; } else if (numCharts <= 4) { rows = 2; cols = 2; } else if (numCharts <= 6) { rows = 3; cols = 2; } else { rows = 3; cols = 3; } const subChartWidth = chartWidth / cols; const subChartHeight = chartHeight / rows; const chartArea = svg.append("g").attr("transform", `translate(${margin.left}, ${margin.top})`); // 为每个x值创建子图 uniqueXValues.forEach((xValue, index) => { const row = Math.floor(index / cols); const col = index % cols; const subChartX = col * subChartWidth; const subChartY = row * subChartHeight; const subChart = chartArea.append("g") .attr("class", "other") .attr("transform", `translate(${subChartX}, ${subChartY})`); // 计算仪表盘参数 - 优化空间利用 const centerX = subChartWidth / 2; const centerY = subChartHeight * 0.75; // 圆心下移,给标签留更少空间 // 增大半圆占用比例,减少边距浪费 const maxRadius = Math.min(subChartWidth * 0.95, (subChartHeight - 30) * 0.8) / 2; // 宽度用95%,高度考虑标签后用80% const categoryData = groupedData[xValue]; const arcThickness = Math.max(8, maxRadius / (categoryData.length + 1)); const gapBetweenLayers = Math.max(2, arcThickness * 0.15); // 添加x标签,紧贴在半圆上方 const labelY = centerY - maxRadius - 8; // 减小标签与半圆的间距 subChart.append("text") .attr("x", subChartWidth / 2) .attr("y", labelY) .attr("text-anchor", "middle") .attr("font-size", "14px") .attr("font-weight", "bold") .attr("fill", colorResolver.text({ fallback: "#333" }).value) .attr("class", "label") .text(xValue); const startAngle = -Math.PI / 2; const endAngle = Math.PI / 2; const gaugeGroup = subChart.append("g") .attr("class", "other") .attr("transform", `translate(${centerX}, ${centerY})`); // 为每个group创建同心圆弧 categoryData.forEach((d, i) => { const outerRadius = maxRadius - i * (arcThickness + gapBetweenLayers); const innerRadius = outerRadius - arcThickness; // 背景弧 const backgroundArc = d3.arc() .innerRadius(innerRadius) .outerRadius(outerRadius) .startAngle(startAngle) .endAngle(endAngle); gaugeGroup.append("path") .attr("class", "mark") .attr("d", backgroundArc) .attr("fill", "#666666") .attr("opacity", 0.3); // 数值弧 const valueArc = d3.arc() .innerRadius(innerRadius) .outerRadius(outerRadius) .startAngle(startAngle); const targetAngle = startAngle + angleScale(d.value); gaugeGroup.append("path") .attr("class", "mark") .attr("d", valueArc({ startAngle: startAngle, endAngle: targetAngle })) .attr("fill", d.color) .style("filter", variables.has_shadow ? "drop-shadow(0 2px 4px rgba(0,0,0,0.15))" : "none"); // 数值标签 const labelRadius = (innerRadius + outerRadius) / 2; const labelAngle = Math.PI; const labelX = labelRadius * Math.cos(labelAngle); const labelY = labelRadius * Math.sin(labelAngle) + arcThickness * 0.5; const maxFontSize = Math.min(arcThickness * 0.6, 12); const minFontSize = Math.max(5, arcThickness * 0.3); let fontSize = maxFontSize; const valueLabel = chartUtils.format.scaledText(d.value); const textWidth = chartUtils.text.measure(gaugeGroup, valueLabel, { fontSize, fontWeight: "bold" }).width; const availableWidth = arcThickness * 1.5; if (textWidth > availableWidth) { fontSize = Math.max(minFontSize, fontSize * availableWidth / textWidth); } gaugeGroup.append("text") .attr("class", "value") .attr("x", labelX) .attr("y", labelY) .attr("text-anchor", "middle") .attr("dominant-baseline", "central") .attr("font-size", fontSize + "px") .attr("font-weight", "bold") .attr("fill", d.color) .text(chartUtils.format.scaledText(d.value)); }); }); return svg.node();} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329/*REQUIREMENTS_BEGIN{ "chart_type": "Small Multiples of Gauge Chart", "chart_name": "small_multiples_gauge_plain_chart_02", "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 9], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": [], "min_height": 400, "min_width": 600, "background": "light", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, dataJSON) { const jsonData = dataJSON || {}; const dataColumns = chartUtils.schema.columns(jsonData); const colorResolver = chartUtils.color.resolver(jsonData); const chartUtilsFormatSample = chartUtils.format.autoText; const chartUtilsTextSample = chartUtils.text.estimate; const chartUtilsStandard = { schema: chartUtils.schema, format: chartUtils.format, text: chartUtils.text, color: chartUtils.color, legendLayout: chartUtils.legend.layout, legendDraw: chartUtils.legend.draw, random: chartUtils.random.generator(jsonData, "dev-wz-style") }; const standardChannels = chartUtils.schema.channels(jsonData, { x: { fallbackIndex: 0 }, y: { fallbackIndex: 1 }, y2: { fallbackIndex: 2 }, y3: { fallbackIndex: 3 }, size: { fallbackIndex: 2 }, group: { fallbackIndex: 2 }, group2: { fallbackIndex: 3 }, group3: { fallbackIndex: 4 } }); const dataBlock = jsonData.data || {}; const sourceRows = dataBlock.data || []; const columns = dataBlock.columns || []; const variables = jsonData.variables || {}; const typography = jsonData.typography || {}; const sourceColors = jsonData.colors || {};
d3.select(containerSelector).html("");
const categoryColumn = chartUtils.schema.channel(jsonData, "x", { fallbackIndex: 0 }).raw || {}; const valueColumn = chartUtils.schema.channel(jsonData, "y", { fallbackIndex: 1 }).raw || {}; const categoryField = categoryColumn.name; const valueField = valueColumn.name; const valueUnit = valueColumn.unit === "none" ? "" : (valueColumn.unit || "");
const width = Math.max(460, Number(variables.width) || 600); const baseHeight = Math.max(400, Number(variables.height) || 520); const fontFamily = typography.label?.font_family || typography.title?.font_family || "Arial, sans-serif"; const annotationFamily = typography.annotation?.font_family || fontFamily; const textColor = sourceColors.text_color || "#1f2937"; const mutedText = "#64748b"; const primaryColor = sourceColors.other?.primary || sourceColors.available_colors?.[0] || "#2563eb"; const trackColor = "rgba(100, 116, 139, 0.20)"; const labelSize = Math.max(8.5, Math.min(11, parseFloat(typography.label?.font_size) || 10)); const valueSize = Math.max(11, Math.min(16, parseFloat(typography.annotation?.font_size) || 13)); const tickSize = Math.max(7.5, Math.min(9, valueSize - 3)); const labelWeight = typography.label?.font_weight || "700"; const valueWeight = typography.annotation?.font_weight || "750";
const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink") .attr("class", "small-multiples-gauge-chart-02");
function message(text) { svg.attr("height", baseHeight).attr("viewBox", `0 0 ${width} ${baseHeight}`); svg.append("text") .attr("x", width / 2) .attr("y", baseHeight / 2) .attr("text-anchor", "middle") .attr("fill", textColor) .style("font-family", fontFamily) .style("font-size", "16px") .text(text); return svg.node(); }
if (!categoryField || !valueField) return message("Missing gauge fields");
function readableLabel(value) { return String(value ?? "") .replace(/_/g, " ") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/\s+/g, " ") .trim(); }
function parseTemporalRank(value) { const text = String(value ?? "").trim(); const lower = text.toLowerCase(); const months = { jan: 1, january: 1, feb: 2, february: 2, mar: 3, march: 3, apr: 4, april: 4, may: 5, jun: 6, june: 6, jul: 7, july: 7, aug: 8, august: 8, sep: 9, sept: 9, september: 9, oct: 10, october: 10, nov: 11, november: 11, dec: 12, december: 12 }; if (months[lower] != null) return months[lower]; let match = text.match(/^(-?\d{4})$/); if (match) return Number(match[1]) * 10000; match = text.match(/^(-?\d{4})[-/.](\d{1,2})(?:[-/.](\d{1,2}))?$/); if (match) return Number(match[1]) * 10000 + Number(match[2]) * 100 + Number(match[3] || 1); match = text.match(/^Q([1-4])\s+(-?\d{4})$/i); if (match) return Number(match[2]) * 10 + Number(match[1]); match = text.match(/^(-?\d{4})\s+Q([1-4])$/i); if (match) return Number(match[1]) * 10 + Number(match[2]); return NaN; }
function parseOrdinalRank(value) { const text = String(value ?? "").trim().toLowerCase(); const named = { low: 1, lower: 1, medium: 2, moderate: 2, high: 3, higher: 3 }; if (named[text] != null) return named[text]; let match = text.match(/^(-?\d+(?:\.\d+)?)/); if (match) return Number(match[1]); return NaN; }
function compactNumber(value) { const numeric = Number(value); const abs = Math.abs(numeric); if (abs >= 1000000000) return `${d3.format(".3~g")(numeric / 1000000000)}B`; if (abs >= 1000000) return `${d3.format(".3~g")(numeric / 1000000)}M`; if (abs >= 1000) return `${d3.format(".3~g")(numeric / 1000)}K`; return d3.format(",.4~g")(numeric); }
function formatLocalValue(value, unit = "") { const numeric = Number(value); const formatted = compactNumber(numeric); if (!unit) return formatted; if (unit === "%") return `${formatted}%`; if (unit.startsWith("$")) return `$${compactNumber(Math.abs(numeric))}${unit.slice(1)}`; if (unit.length <= 3 && /^[^A-Za-z0-9]+$/.test(unit)) return `${unit}${formatted}`; return `${formatted} ${unit}`; }
function truncateText(text, maxChars) { if (text.length <= maxChars) return text; return `${text.slice(0, Math.max(1, maxChars - 3)).trim()}...`; }
const aggregated = new Map(); sourceRows.forEach((row, index) => { const category = readableLabel(row[categoryField]); const value = Number(row[valueField]); if (!category || !Number.isFinite(value) || value < 0) return; if (!aggregated.has(category)) { aggregated.set(category, { category, rawCategory: row[categoryField], firstIndex: index, value: 0 }); } aggregated.get(category).value += value; });
const rows = Array.from(aggregated.values()).map(row => ({ ...row, temporalRank: parseTemporalRank(row.rawCategory), ordinalRank: parseOrdinalRank(row.rawCategory) })); if (!rows.length) return message("No valid data for gauges");
const allTemporal = categoryColumn.data_type === "temporal" || rows.every(d => Number.isFinite(d.temporalRank)); const allOrdinal = !allTemporal && rows.every(d => Number.isFinite(d.ordinalRank)); const sortMode = allTemporal ? "chronological" : (allOrdinal ? "ordered category" : "largest value"); rows.sort((a, b) => { if (allTemporal) return d3.ascending(a.temporalRank, b.temporalRank) || d3.ascending(a.firstIndex, b.firstIndex); if (allOrdinal) return d3.ascending(a.ordinalRank, b.ordinalRank) || d3.ascending(a.firstIndex, b.firstIndex); return d3.descending(a.value, b.value) || d3.ascending(a.category, b.category); });
const count = rows.length; const cols = count <= 2 ? count : (count <= 4 ? 2 : 3); const panelRows = Math.ceil(count / cols); const outer = { top: 36, right: 26, bottom: 52, left: 26 }; const gapX = 22; const gapY = 28; const minPanelHeight = count <= 3 ? 170 : 140; const height = Math.max(baseHeight, outer.top + outer.bottom + panelRows * minPanelHeight + (panelRows - 1) * gapY); svg.attr("height", height).attr("viewBox", `0 0 ${width} ${height}`);
const panelWidth = (width - outer.left - outer.right - gapX * (cols - 1)) / cols; const panelHeight = (height - outer.top - outer.bottom - gapY * (panelRows - 1)) / panelRows; const maxValue = d3.max(rows, d => d.value) || 0; const gaugeMax = d3.scaleLinear().domain([0, maxValue || 1]).nice(4).domain()[1] || 1; const angleScale = d3.scaleLinear().domain([0, gaugeMax]).range([-Math.PI * 0.72, Math.PI * 0.72]).clamp(true); const startAngle = -Math.PI * 0.72; const endAngle = Math.PI * 0.72;
rows.forEach((row, index) => { const gridRow = Math.floor(index / cols); const gridCol = index % cols; const x = outer.left + gridCol * (panelWidth + gapX); const y = outer.top + gridRow * (panelHeight + gapY); const centerX = panelWidth / 2; const centerY = panelHeight * 0.58; const radius = Math.max(38, Math.min(panelWidth * 0.34, panelHeight * 0.34)); const thickness = Math.max(10, radius * 0.22); const innerRadius = radius - thickness;
const panel = svg.append("g") .attr("class", "gauge-panel") .attr("data-category", row.category) .attr("transform", `translate(${x}, ${y})`);
panel.append("rect") .attr("class", "panel-background") .attr("x", 0) .attr("y", 0) .attr("width", panelWidth) .attr("height", panelHeight) .attr("rx", 5) .attr("fill", "rgba(255, 255, 255, 0.22)") .attr("stroke", "rgba(100, 116, 139, 0.16)");
panel.append("text") .attr("class", "category-label") .attr("data-category", row.category) .attr("x", centerX) .attr("y", 18) .attr("text-anchor", "middle") .attr("fill", textColor) .style("font-family", fontFamily) .style("font-size", `${labelSize}px`) .style("font-weight", labelWeight) .text(truncateText(row.category, Math.max(10, Math.floor(panelWidth / 8))));
const gauge = panel.append("g") .attr("class", "gauge") .attr("transform", `translate(${centerX}, ${centerY})`);
const trackArc = d3.arc() .innerRadius(innerRadius) .outerRadius(radius) .startAngle(startAngle) .endAngle(endAngle); const valueArc = d3.arc() .innerRadius(innerRadius) .outerRadius(radius) .startAngle(startAngle) .endAngle(angleScale(row.value));
gauge.append("path") .attr("class", "gauge-track") .attr("d", trackArc) .attr("fill", trackColor);
gauge.append("path") .attr("class", "gauge-value-arc data-point mark") .attr("data-category", row.category) .attr("data-value", row.value) .attr("data-scale-max", gaugeMax) .attr("d", valueArc) .attr("fill", primaryColor);
const tickAngles = [startAngle, endAngle]; tickAngles.forEach((angle, tickIndex) => { const tx = Math.sin(angle) * (radius + 4); const ty = -Math.cos(angle) * (radius + 4); panel.append("text") .attr("class", "gauge-tick") .attr("x", centerX + tx) .attr("y", centerY + ty + 4) .attr("text-anchor", tickIndex === 0 ? "end" : "start") .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", `${tickSize}px`) .style("font-weight", valueWeight) .text(tickIndex === 0 ? "0" : formatLocalValue(gaugeMax, valueUnit)); });
panel.append("text") .attr("class", "value-label") .attr("data-category", row.category) .attr("x", centerX) .attr("y", centerY + radius * 0.42) .attr("text-anchor", "middle") .attr("fill", primaryColor) .style("font-family", annotationFamily) .style("font-size", `${valueSize}px`) .style("font-weight", valueWeight) .text(formatLocalValue(row.value, valueUnit)); });
svg.append("text") .attr("class", "scale-note") .attr("x", width / 2) .attr("y", height - 28) .attr("text-anchor", "middle") .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", `${Math.max(8, tickSize)}px`) .text(`${readableLabel(valueColumn.label || valueField)} gauge scale: 0-${formatLocalValue(gaugeMax, valueUnit)}; arcs use actual values only`);
svg.append("text") .attr("class", "category-note") .attr("x", width / 2) .attr("y", height - 12) .attr("text-anchor", "middle") .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", `${Math.max(7.5, tickSize - 1)}px`) .text(`${readableLabel(categoryColumn.label || categoryField)} order: ${sortMode}; decorative images removed`);
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333/*REQUIREMENTS_BEGIN{ "chart_type": "Small Multiples of Gauge Chart", "chart_name": "small_multiples_gauge_plain_chart_03", "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 9], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": [], "min_height": 400, "min_width": 600, "background": "light", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, dataJSON) { const jsonData = dataJSON || {}; const dataColumns = chartUtils.schema.columns(jsonData); const colorResolver = chartUtils.color.resolver(jsonData); const chartUtilsFormatSample = chartUtils.format.autoText; const chartUtilsTextSample = chartUtils.text.estimate; const chartUtilsStandard = { schema: chartUtils.schema, format: chartUtils.format, text: chartUtils.text, color: chartUtils.color, legendLayout: chartUtils.legend.layout, legendDraw: chartUtils.legend.draw, random: chartUtils.random.generator(jsonData, "dev-wz-style") }; const standardChannels = chartUtils.schema.channels(jsonData, { x: { fallbackIndex: 0 }, y: { fallbackIndex: 1 }, y2: { fallbackIndex: 2 }, y3: { fallbackIndex: 3 }, size: { fallbackIndex: 2 }, group: { fallbackIndex: 2 }, group2: { fallbackIndex: 3 }, group3: { fallbackIndex: 4 } }); const dataBlock = jsonData.data || {}; const sourceRows = dataBlock.data || []; const columns = dataBlock.columns || []; const variables = jsonData.variables || {}; const typography = jsonData.typography || {}; const sourceColors = jsonData.colors || {};
d3.select(containerSelector).html("");
const categoryColumn = chartUtils.schema.channel(jsonData, "x", { fallbackIndex: 0 }).raw || {}; const valueColumn = chartUtils.schema.channel(jsonData, "y", { fallbackIndex: 1 }).raw || {}; const categoryField = categoryColumn.name; const valueField = valueColumn.name; const valueUnit = valueColumn.unit === "none" ? "" : (valueColumn.unit || "");
const width = Math.max(460, Number(variables.width) || 600); const baseHeight = Math.max(400, Number(variables.height) || 520); const fontFamily = typography.label?.font_family || typography.title?.font_family || "Arial, sans-serif"; const annotationFamily = typography.annotation?.font_family || fontFamily; const textColor = sourceColors.text_color || "#1f2937"; const mutedText = "#64748b"; const primaryColor = sourceColors.other?.primary || sourceColors.available_colors?.[0] || "#2563eb"; const trackColor = "rgba(100, 116, 139, 0.20)"; const labelSize = Math.max(8.5, Math.min(11, parseFloat(typography.label?.font_size) || 10)); const valueSize = Math.max(11, Math.min(16, parseFloat(typography.annotation?.font_size) || 13)); const tickSize = Math.max(7.5, Math.min(9, valueSize - 3)); const labelWeight = typography.label?.font_weight || "700"; const valueWeight = typography.annotation?.font_weight || "750";
const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink") .attr("class", "small-multiples-gauge-chart-03");
function message(text) { svg.attr("height", baseHeight).attr("viewBox", `0 0 ${width} ${baseHeight}`); svg.append("text") .attr("x", width / 2) .attr("y", baseHeight / 2) .attr("text-anchor", "middle") .attr("fill", textColor) .style("font-family", fontFamily) .style("font-size", "16px") .text(text); return svg.node(); }
if (!categoryField || !valueField) return message("Missing gauge fields");
function readableLabel(value) { return String(value ?? "") .replace(/_/g, " ") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/\s+/g, " ") .trim(); }
function parseTemporalRank(value) { const text = String(value ?? "").trim(); const lower = text.toLowerCase(); const months = { jan: 1, january: 1, feb: 2, february: 2, mar: 3, march: 3, apr: 4, april: 4, may: 5, jun: 6, june: 6, jul: 7, july: 7, aug: 8, august: 8, sep: 9, sept: 9, september: 9, oct: 10, october: 10, nov: 11, november: 11, dec: 12, december: 12 }; if (months[lower] != null) return months[lower]; let match = text.match(/^(-?\d{4})$/); if (match) return Number(match[1]) * 10000; match = text.match(/^(-?\d{4})[-/.](\d{1,2})(?:[-/.](\d{1,2}))?$/); if (match) return Number(match[1]) * 10000 + Number(match[2]) * 100 + Number(match[3] || 1); match = text.match(/^Q([1-4])\s+(-?\d{4})$/i); if (match) return Number(match[2]) * 10 + Number(match[1]); match = text.match(/^(-?\d{4})\s+Q([1-4])$/i); if (match) return Number(match[1]) * 10 + Number(match[2]); return NaN; }
function parseOrdinalRank(value) { const text = String(value ?? "").trim().toLowerCase(); const named = { "very easy": 1, easy: 2, "slightly easy": 3, moderate: 4, "somewhat difficult": 5, difficult: 6, "very difficult": 7, "extremely difficult": 8, low: 1, lower: 1, medium: 2, high: 3, higher: 3 }; if (named[text] != null) return named[text]; let match = text.match(/(?:less than|under)\s*([\d,]+)/); if (match) return Number(match[1].replace(/,/g, "")) - 0.5; match = text.match(/^([\d,]+(?:\.\d+)?)\s*(?:-|to)/); if (match) return Number(match[1].replace(/,/g, "")); match = text.match(/(?:more than|over)\s*([\d,]+)/); if (match) return Number(match[1].replace(/,/g, "")) + 0.5; match = text.match(/^(-?\d+(?:\.\d+)?)/); if (match) return Number(match[1]); return NaN; }
function compactNumber(value) { const numeric = Number(value); const abs = Math.abs(numeric); if (abs >= 1000000000) return `${d3.format(".3~g")(numeric / 1000000000)}B`; if (abs >= 1000000) return `${d3.format(".3~g")(numeric / 1000000)}M`; if (abs >= 1000) return `${d3.format(".3~g")(numeric / 1000)}K`; return d3.format(",.4~g")(numeric); }
function formatLocalValue(value, unit = "") { const numeric = Number(value); const formatted = compactNumber(numeric); if (!unit) return formatted; if (unit === "%") return `${formatted}%`; if (unit.startsWith("$")) return `$${compactNumber(Math.abs(numeric))}${unit.slice(1)}`; if (unit.length <= 3 && /^[^A-Za-z0-9]+$/.test(unit)) return `${unit}${formatted}`; return `${formatted} ${unit}`; }
function truncateText(text, maxChars) { if (text.length <= maxChars) return text; return `${text.slice(0, Math.max(1, maxChars - 3)).trim()}...`; }
const rows = []; const seen = new Set(); sourceRows.forEach((row, index) => { const category = readableLabel(row[categoryField]); const value = Number(row[valueField]); if (!category || !Number.isFinite(value) || value < 0 || seen.has(category)) return; seen.add(category); rows.push({ category, rawCategory: row[categoryField], firstIndex: index, value, temporalRank: parseTemporalRank(row[categoryField]), ordinalRank: parseOrdinalRank(row[categoryField]) }); }); if (!rows.length) return message("No valid data for gauges");
const allTemporal = categoryColumn.data_type === "temporal" || rows.every(d => Number.isFinite(d.temporalRank)); const allOrdinal = !allTemporal && rows.every(d => Number.isFinite(d.ordinalRank)); const sortMode = allTemporal ? "chronological" : (allOrdinal ? "ordered category" : "largest value"); rows.sort((a, b) => { if (allTemporal) return d3.ascending(a.temporalRank, b.temporalRank) || d3.ascending(a.firstIndex, b.firstIndex); if (allOrdinal) return d3.ascending(a.ordinalRank, b.ordinalRank) || d3.ascending(a.firstIndex, b.firstIndex); return d3.descending(a.value, b.value) || d3.ascending(a.category, b.category); });
const count = rows.length; const cols = count <= 2 ? count : (count <= 4 ? 2 : 3); const panelRows = Math.ceil(count / cols); const outer = { top: 36, right: 26, bottom: 52, left: 26 }; const gapX = 22; const gapY = 28; const minPanelHeight = count <= 3 ? 170 : 140; const height = Math.max(baseHeight, outer.top + outer.bottom + panelRows * minPanelHeight + (panelRows - 1) * gapY); svg.attr("height", height).attr("viewBox", `0 0 ${width} ${height}`);
const panelWidth = (width - outer.left - outer.right - gapX * (cols - 1)) / cols; const panelHeight = (height - outer.top - outer.bottom - gapY * (panelRows - 1)) / panelRows; const maxValue = d3.max(rows, d => d.value) || 0; const gaugeMax = d3.scaleLinear().domain([0, maxValue || 1]).nice(4).domain()[1] || 1; const startAngle = -Math.PI * 0.72; const endAngle = Math.PI * 0.72; const angleScale = d3.scaleLinear().domain([0, gaugeMax]).range([startAngle, endAngle]).clamp(true);
rows.forEach((row, index) => { const gridRow = Math.floor(index / cols); const gridCol = index % cols; const x = outer.left + gridCol * (panelWidth + gapX); const y = outer.top + gridRow * (panelHeight + gapY); const centerX = panelWidth / 2; const centerY = panelHeight * 0.58; const radius = Math.max(38, Math.min(panelWidth * 0.34, panelHeight * 0.34)); const thickness = Math.max(10, radius * 0.22); const innerRadius = radius - thickness;
const panel = svg.append("g") .attr("class", "gauge-panel") .attr("data-category", row.category) .attr("transform", `translate(${x}, ${y})`);
panel.append("rect") .attr("class", "panel-background") .attr("x", 0) .attr("y", 0) .attr("width", panelWidth) .attr("height", panelHeight) .attr("rx", 5) .attr("fill", "rgba(255, 255, 255, 0.22)") .attr("stroke", "rgba(100, 116, 139, 0.16)");
panel.append("text") .attr("class", "category-label") .attr("data-category", row.category) .attr("x", centerX) .attr("y", 18) .attr("text-anchor", "middle") .attr("fill", textColor) .style("font-family", fontFamily) .style("font-size", `${labelSize}px`) .style("font-weight", labelWeight) .text(truncateText(row.category, Math.max(10, Math.floor(panelWidth / 8))));
const gauge = panel.append("g") .attr("class", "gauge") .attr("transform", `translate(${centerX}, ${centerY})`);
const trackArc = d3.arc() .innerRadius(innerRadius) .outerRadius(radius) .startAngle(startAngle) .endAngle(endAngle); const valueArc = d3.arc() .innerRadius(innerRadius) .outerRadius(radius) .startAngle(startAngle) .endAngle(angleScale(row.value));
gauge.append("path") .attr("class", "gauge-track") .attr("d", trackArc) .attr("fill", trackColor);
gauge.append("path") .attr("class", "gauge-value-arc data-point mark") .attr("data-category", row.category) .attr("data-value", row.value) .attr("data-scale-max", gaugeMax) .attr("d", valueArc) .attr("fill", primaryColor);
[startAngle, endAngle].forEach((angle, tickIndex) => { const tx = Math.sin(angle) * (radius + 4); const ty = -Math.cos(angle) * (radius + 4); panel.append("text") .attr("class", "gauge-tick") .attr("x", centerX + tx) .attr("y", centerY + ty + 4) .attr("text-anchor", tickIndex === 0 ? "end" : "start") .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", `${tickSize}px`) .style("font-weight", valueWeight) .text(tickIndex === 0 ? "0" : formatLocalValue(gaugeMax, valueUnit)); });
panel.append("text") .attr("class", "value-label") .attr("data-category", row.category) .attr("x", centerX) .attr("y", centerY + radius * 0.42) .attr("text-anchor", "middle") .attr("fill", primaryColor) .style("font-family", annotationFamily) .style("font-size", `${valueSize}px`) .style("font-weight", valueWeight) .text(formatLocalValue(row.value, valueUnit)); });
svg.append("text") .attr("class", "scale-note") .attr("x", width / 2) .attr("y", height - 28) .attr("text-anchor", "middle") .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", `${Math.max(8, tickSize)}px`) .text(`${readableLabel(valueColumn.label || valueField)} gauge scale: 0-${formatLocalValue(gaugeMax, valueUnit)}; arcs use actual values only`);
svg.append("text") .attr("class", "category-note") .attr("x", width / 2) .attr("y", height - 12) .attr("text-anchor", "middle") .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", `${Math.max(7.5, tickSize - 1)}px`) .text(`${readableLabel(categoryColumn.label || categoryField)} order: ${sortMode}; decorative images removed`);
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548/*REQUIREMENTS_BEGIN{ "chart_type": "Small Multiples of Gauge Charts", "chart_name": "small_multiples_gauge_plain_chart_04", "is_composite": false, "required_fields": ["x","y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 10], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "stroke"], "min_height": 300, "min_width": 300, "background": "no", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const jsonData = data || {}; const dataColumns = chartUtils.schema.columns(jsonData); const colorResolver = chartUtils.color.resolver(jsonData); const chartUtilsFormatSample = chartUtils.format.autoText; const chartUtilsTextSample = chartUtils.text.estimate; const chartUtilsStandard = { schema: chartUtils.schema, format: chartUtils.format, text: chartUtils.text, color: chartUtils.color, legendLayout: chartUtils.legend.layout, legendDraw: chartUtils.legend.draw, random: chartUtils.random.generator(jsonData, "dev-wz-style") }; const standardChannels = chartUtils.schema.channels(jsonData, { x: { fallbackIndex: 0 }, y: { fallbackIndex: 1 }, y2: { fallbackIndex: 2 }, y3: { fallbackIndex: 3 }, size: { fallbackIndex: 2 }, group: { fallbackIndex: 2 }, group2: { fallbackIndex: 3 }, group3: { fallbackIndex: 4 } }); const dataBlock = jsonData.data || {}; const chartData = dataBlock.data || []; const variables = jsonData.variables || {}; const typography = jsonData.typography || { label: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } }; const sourceColors = jsonData.colors || {};
d3.select(containerSelector).html("");
const dimensionColumn = chartUtils.schema.channel(jsonData, "x", { fallbackIndex: 0 }).raw || {}; const valueColumn = chartUtils.schema.channel(jsonData, "y", { fallbackIndex: 1 }).raw || {}; const dimensionField = dimensionColumn.name; const valueField = valueColumn.name; const valueUnit = valueColumn.unit && valueColumn.unit !== "none" ? valueColumn.unit : "";
const width = Math.max(430, Number(variables.width) || 600); const requestedHeight = Number(variables.height) || 390; const fontFamily = typography.label?.font_family || typography.title?.font_family || "Arial, sans-serif"; const annotationFamily = typography.annotation?.font_family || fontFamily; const labelWeight = typography.label?.font_weight || "700"; const valueWeight = typography.annotation?.font_weight || "800"; const textColor = sourceColors.text_color || "#182638"; const mutedText = "#617184"; const greenDark = "#1f7b3a"; const green = "#63ad4b"; const greenLight = "#b8db76"; const blueDark = "#07549f"; const blue = "#1b78c8"; const blueLight = "#a9d5f7"; const panelFill = "#ffffff"; const softPanel = "#f6f9fb";
function message(text) { const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", requestedHeight) .attr("viewBox", `0 0 ${width} ${requestedHeight}`) .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); svg.append("text") .attr("x", width / 2) .attr("y", requestedHeight / 2) .attr("text-anchor", "middle") .attr("fill", textColor) .style("font-family", fontFamily) .style("font-size", "15px") .text(text); return svg.node(); }
if (!dimensionField || !valueField) return message("Missing gauge fields");
function readableLabel(value) { return String(value ?? "") .replace(/_/g, " ") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/\s+/g, " ") .trim(); }
function parseTemporalSortValue(value) { const text = String(value ?? "").trim(); let match = text.match(/^(-?\d{1,6})$/); if (match) return Number(match[1]); match = text.match(/^(-?\d{1,6})[-/.](\d{1,2})(?:[-/.](\d{1,2}))?$/); if (match) return Number(match[1]) * 10000 + Number(match[2]) * 100 + Number(match[3] || 1); return NaN; }
function compactNumber(value) { const numericValue = Number(value); if (!Number.isFinite(numericValue)) return String(value ?? ""); const absValue = Math.abs(numericValue); if (absValue >= 1000000000) return `${d3.format(".3~g")(numericValue / 1000000000)}B`; if (absValue >= 1000000) return `${d3.format(".3~g")(numericValue / 1000000)}M`; if (absValue >= 1000) return `${d3.format(".3~g")(numericValue / 1000)}K`; return d3.format(",.4~g")(numericValue); }
function formatLocalValue(value) { const formatted = compactNumber(value); if (!valueUnit) return formatted; if (valueUnit === "%") return `${formatted}%`; if (valueUnit.length <= 3 && /^[^A-Za-z0-9]+$/.test(valueUnit)) return `${valueUnit}${formatted}`; return `${formatted} ${valueUnit}`; }
function fontSizeFor(text, maxWidth, baseSize, minSize = 7.2) { const estimated = String(text ?? "").length * baseSize * 0.55; if (estimated <= maxWidth) return baseSize; return Math.max(minSize, Math.min(baseSize, maxWidth / Math.max(1, String(text ?? "").length * 0.55))); }
function fitText(selection, text, maxWidth, baseSize, minSize = 7.2) { const size = fontSizeFor(text, maxWidth, baseSize, minSize); selection.style("font-size", `${size}px`).text(text); const estimated = String(text ?? "").length * size * 0.55; if (estimated > maxWidth) { selection.attr("textLength", maxWidth).attr("lengthAdjust", "spacingAndGlyphs"); } return selection; }
const cleanedData = chartData .map((row, index) => ({ row, sourceIndex: index, category: readableLabel(row[dimensionField]), rawCategory: row[dimensionField], value: Number(row[valueField]), temporal: parseTemporalSortValue(row[dimensionField]) })) .filter(d => d.category && Number.isFinite(d.value) && d.value >= 0);
if (!cleanedData.length) return message("No valid gauge data");
const hasTemporalLikeX = ( dimensionColumn.data_type === "temporal" || cleanedData.every(d => Number.isFinite(d.temporal)) ); cleanedData.sort((a, b) => { if (hasTemporalLikeX && Number.isFinite(a.temporal) && Number.isFinite(b.temporal)) { return d3.ascending(a.temporal, b.temporal) || d3.ascending(a.sourceIndex, b.sourceIndex); } return d3.descending(a.value, b.value) || d3.ascending(a.sourceIndex, b.sourceIndex); });
const maxValue = d3.max(cleanedData, d => d.value) || 1; const valueTextForScale = [ valueField, valueColumn.description, valueUnit ].join(" ").toLowerCase(); const looksBoundedToHundred = ( cleanedData.every(d => d.value >= 0 && d.value <= 100) && /%|percent|percentage|share|rate|ratio|index|score/.test(valueTextForScale) ); const gaugeMax = looksBoundedToHundred ? 100 : maxValue;
const count = cleanedData.length; const cols = count <= 3 ? count : Math.min(4, count); const rows = Math.ceil(count / cols); const panelX = 8; const panelY = 8; const panelWidth = width - panelX * 2; const topBandHeight = 88; const footerHeight = 62; const gridGapX = Math.max(10, width * 0.018); const gridGapY = Math.max(16, width * 0.026); const gridX = panelX + 20; const gridWidth = panelWidth - 40; const cardWidth = (gridWidth - gridGapX * (cols - 1)) / cols; const rowHeight = Math.max(132, Math.min(178, cardWidth * 1.08)); const gridY = panelY + topBandHeight + 12; const gridHeight = rows * rowHeight + (rows - 1) * gridGapY; const footerY = gridY + gridHeight + 18; const height = Math.max(360, footerY + footerHeight + 12); const panelHeight = height - panelY * 2;
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") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink") .attr("class", "small-multiples-gauge-chart-04");
const defs = svg.append("defs"); const safeId = chartUtils.random.value(jsonData, "small_multiples_gauge_plain_chart_04").toString(36).slice(2, 10); const greenGradientId = `gauge-04-green-${safeId}`; const blueGradientId = `gauge-04-blue-${safeId}`; [greenGradientId, blueGradientId].forEach((id, idx) => { const colorsForGradient = idx === 0 ? [{ offset: "0%", color: greenDark }, { offset: "58%", color: green }, { offset: "100%", color: greenLight }] : [{ offset: "0%", color: blueDark }, { offset: "60%", color: blue }, { offset: "100%", color: blueLight }]; defs.append("linearGradient") .attr("id", id) .attr("x1", "0%") .attr("x2", "100%") .attr("y1", "0%") .attr("y2", "0%") .selectAll("stop") .data(colorsForGradient) .enter() .append("stop") .attr("offset", d => d.offset) .attr("stop-color", d => d.color); });
svg.append("rect") .attr("class", "chart-style-panel") .attr("x", panelX) .attr("y", panelY) .attr("width", panelWidth) .attr("height", panelHeight) .attr("rx", 10) .attr("fill", panelFill) .attr("stroke", "rgba(38, 77, 116, 0.14)");
svg.append("rect") .attr("class", "reference-icon-slot chart-icon-slot") .attr("data-slot", "icon") .attr("x", panelX + 20) .attr("y", panelY + 17) .attr("width", 46) .attr("height", 46) .attr("rx", 11) .attr("fill", "#eef7ef") .attr("stroke", "rgba(31, 123, 58, 0.24)"); svg.append("path") .attr("class", "reference-icon-slot-glyph") .attr("d", `M${panelX + 33},${panelY + 48} C${panelX + 39},${panelY + 27} ${panelX + 58},${panelY + 25} ${panelX + 55},${panelY + 48}`) .attr("fill", "none") .attr("stroke", green) .attr("stroke-width", 5) .attr("stroke-linecap", "round");
const metricTitle = readableLabel(valueColumn.label || valueField || valueColumn.description); svg.append("text") .attr("class", "scale-note") .attr("x", panelX + 80) .attr("y", panelY + 34) .attr("fill", "#17324d") .style("font-family", annotationFamily) .style("font-size", "11px") .style("font-weight", "800") .text(metricTitle); svg.append("text") .attr("class", "category-note") .attr("x", panelX + 80) .attr("y", panelY + 54) .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", "9px") .style("font-weight", "650") .text(`${readableLabel(dimensionColumn.label || dimensionField)} ranked by ${hasTemporalLikeX ? "time" : "value"}`);
const decorX = panelX + panelWidth - 111; svg.append("rect") .attr("class", "reference-decorative-image-slot decorative-image-slot") .attr("data-slot", "decorative-image") .attr("x", decorX) .attr("y", panelY + 16) .attr("width", 88) .attr("height", 48) .attr("rx", 12) .attr("fill", softPanel) .attr("stroke", "rgba(7, 84, 159, 0.18)"); svg.append("circle") .attr("class", "reference-decorative-image-dot") .attr("cx", decorX + 25) .attr("cy", panelY + 40) .attr("r", 13) .attr("fill", greenLight); svg.append("path") .attr("class", "reference-decorative-image-wave") .attr("d", `M${decorX + 43},${panelY + 47} C${decorX + 53},${panelY + 20} ${decorX + 71},${panelY + 61} ${decorX + 80},${panelY + 29}`) .attr("fill", "none") .attr("stroke", blue) .attr("stroke-width", 5) .attr("stroke-linecap", "round");
const startAngle = -Math.PI * 0.78; const endAngle = Math.PI * 0.78;
cleanedData.forEach((d, index) => { const row = Math.floor(index / cols); const col = index % cols; const rowCount = Math.min(cols, count - row * cols); const rowOffset = (cols - rowCount) * (cardWidth + gridGapX) / 2; const x = gridX + rowOffset + col * (cardWidth + gridGapX); const y = gridY + row * (rowHeight + gridGapY); const isBlue = row % 2 === 1; const accent = isBlue ? blue : green; const accentDark = isBlue ? blueDark : greenDark; const accentPale = isBlue ? blueLight : greenLight; const gradientId = isBlue ? blueGradientId : greenGradientId; const metricHeight = Math.max(38, Math.min(48, rowHeight * 0.30)); const gaugeCenterX = x + cardWidth / 2; const gaugeCenterY = y + metricHeight + Math.max(48, rowHeight * 0.36); const radius = Math.max(23, Math.min(cardWidth * 0.32, rowHeight * 0.28)); const arcThickness = Math.max(7, radius * 0.22); const percent = Math.max(0, Math.min(d.value / gaugeMax, 1)); const valueAngle = startAngle + (endAngle - startAngle) * percent; const trackArc = d3.arc() .innerRadius(radius - arcThickness) .outerRadius(radius) .startAngle(startAngle) .endAngle(endAngle); const valueArc = d3.arc() .innerRadius(radius - arcThickness) .outerRadius(radius) .startAngle(startAngle) .endAngle(valueAngle);
const item = svg.append("g") .attr("class", "gauge") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("data-scale-max", gaugeMax);
item.append("rect") .attr("class", "metric-card gauge-card") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("x", x) .attr("y", y) .attr("width", cardWidth) .attr("height", metricHeight) .attr("rx", 6) .attr("fill", accent) .attr("fill-opacity", 0.94);
const valueText = formatLocalValue(d.value); fitText( item.append("text") .attr("class", "value metric-value") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("x", x + cardWidth / 2) .attr("y", y + metricHeight * 0.43) .attr("text-anchor", "middle") .attr("dominant-baseline", "middle") .attr("fill", "#ffffff") .style("font-family", annotationFamily) .style("font-weight", valueWeight), valueText, cardWidth - 16, Math.max(12, Math.min(18, metricHeight * 0.34)), 8.2 );
fitText( item.append("text") .attr("class", "label metric-label") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("x", x + cardWidth / 2) .attr("y", y + metricHeight * 0.76) .attr("text-anchor", "middle") .attr("dominant-baseline", "middle") .attr("fill", "#f4fff7") .style("font-family", fontFamily) .style("font-weight", labelWeight), d.category, cardWidth - 14, 8.6, 6.8 );
item.append("rect") .attr("class", "gauge-stage") .attr("x", x) .attr("y", y + metricHeight + 8) .attr("width", cardWidth) .attr("height", rowHeight - metricHeight - 10) .attr("rx", 8) .attr("fill", softPanel) .attr("stroke", "rgba(54, 88, 122, 0.11)");
const face = item.append("g") .attr("class", "gauge-face") .attr("transform", `translate(${gaugeCenterX}, ${gaugeCenterY})`);
face.append("path") .attr("class", "gauge-track") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("d", trackArc) .attr("fill", isBlue ? "#d9edf9" : "#e7f3dc");
face.append("path") .attr("class", "mark gauge-value-arc") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("data-scale-max", gaugeMax) .attr("d", valueArc) .attr("fill", `url(#${gradientId})`) .style("opacity", 0.96);
face.append("circle") .attr("class", "gauge-center-dot") .attr("cx", 0) .attr("cy", 0) .attr("r", Math.max(2.2, radius * 0.07)) .attr("fill", accentDark);
face.append("circle") .attr("class", "gauge-end-dot") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("cx", Math.sin(valueAngle) * (radius - arcThickness / 2)) .attr("cy", -Math.cos(valueAngle) * (radius - arcThickness / 2)) .attr("r", Math.max(2.4, arcThickness * 0.35)) .attr("fill", "#ffffff") .attr("stroke", accentDark) .attr("stroke-width", 1.2);
fitText( item.append("text") .attr("class", "gauge-scale-caption") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("x", gaugeCenterX) .attr("y", Math.min(y + rowHeight - 12, gaugeCenterY + radius + 16)) .attr("text-anchor", "middle") .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-weight", "650"), `${Math.round(percent * 100)}% of scale`, cardWidth - 12, 8.0, 6.8 ); });
const footer = svg.append("g") .attr("class", "reference-footer-card") .attr("transform", `translate(${gridX}, ${footerY})`); footer.append("rect") .attr("class", "footer-card") .attr("x", 0) .attr("y", 0) .attr("width", gridWidth) .attr("height", footerHeight) .attr("rx", 8) .attr("fill", "#f8fbfd") .attr("stroke", "rgba(38, 77, 116, 0.13)");
const footerItems = [ { label: "Scale", text: `0 to ${formatLocalValue(gaugeMax)}` }, { label: "Items", text: `${count} gauges` }, { label: "Encoding", text: "arc length" } ]; const itemWidth = gridWidth / footerItems.length; footerItems.forEach((item, index) => { const itemX = index * itemWidth; if (index > 0) { footer.append("line") .attr("class", "footer-divider") .attr("x1", itemX) .attr("x2", itemX) .attr("y1", 12) .attr("y2", footerHeight - 12) .attr("stroke", "rgba(38, 77, 116, 0.14)"); } footer.append("rect") .attr("class", "footer-icon-slot") .attr("data-slot", `footer-icon-${index + 1}`) .attr("x", itemX + 13) .attr("y", 18) .attr("width", 25) .attr("height", 25) .attr("rx", 7) .attr("fill", index === 1 ? "#eef7ef" : "#eef6fc") .attr("stroke", "rgba(38, 77, 116, 0.18)"); footer.append("circle") .attr("class", "footer-icon-slot-dot") .attr("cx", itemX + 25.5) .attr("cy", 30.5) .attr("r", 5.5) .attr("fill", index === 1 ? green : blue); footer.append("text") .attr("class", "footer-label") .attr("x", itemX + 48) .attr("y", 27) .attr("fill", "#17324d") .style("font-family", annotationFamily) .style("font-size", "8.5px") .style("font-weight", "800") .text(item.label); footer.append("text") .attr("class", "footer-value") .attr("x", itemX + 48) .attr("y", 45) .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", "7.7px") .style("font-weight", "650") .text(item.text); });
return svg.node();}modules/chart_engine/template/d3-js/type71_small_multiples_of_gauge/small_multiples_gauge_plain_chart_01.jsAdded+240
modules/chart_engine/template/d3-js/type71_small_multiples_of_gauge/small_multiples_gauge_plain_chart_02.jsAdded+329
modules/chart_engine/template/d3-js/type71_small_multiples_of_gauge/small_multiples_gauge_plain_chart_03.jsAdded+333
modules/chart_engine/template/d3-js/type71_small_multiples_of_gauge/small_multiples_gauge_plain_chart_04.jsAdded+548