Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_0.jsAdded+464
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_0_test.jsAdded+369
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_0_weilai.jsAdded+318
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_1.jsAdded+361
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_10.jsAdded+859
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_11.jsAdded+574
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_12.jsAdded+719
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_13.jsAdded+531
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_14.jsAdded+736
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_15.jsAdded+444
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_15_hand.jsAdded+483
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_16.jsAdded+630
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_17.jsAdded+617
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_18.jsAdded+356
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_19.jsAdded+326
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_2.jsAdded+216
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_20.jsAdded+405
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_21.jsAdded+615
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_22.jsAdded+522
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_23.jsAdded+724
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_24.jsAdded+397
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_25.jsAdded+332
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_26.jsAdded+434
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_27.jsAdded+435
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_28.jsAdded+588
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_29.jsAdded+589
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_2_hand.jsAdded+234
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_3.jsAdded+224
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_30.jsAdded+440
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_33.jsAdded+603
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_4.jsAdded+525
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_4_hand.jsAdded+584
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_5.jsAdded+384
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_5_hand.jsAdded+407
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_6.jsAdded
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_7.jsAdded+410
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_8.jsAdded+677
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_9.jsAdded+406
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_01.jsAdded+592
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_01_hand.jsAdded+453
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_02.jsAdded+678
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_03.jsAdded+718
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_04.jsAdded+576
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_04_hand.jsAdded+584
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_05.jsAdded+767
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_06.jsAdded+687
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_07.jsAdded+747
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_08.jsAdded+524
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_09.jsAdded
- modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_10.jsAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_0", "is_composite": true, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[3, 20], [0, 100000]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": [], "supported_effects": ["gradient", "opacity", "radius_corner"], "min_height": 300, "min_width": 300, "background": "light", "has_title": "yes", "icon_mark": "none", "icon_label": "none", "has_x_axis": "yes", "has_y_axis": "yes"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); const jsonData = data; const chartData = jsonData.data.data; const variables = jsonData.variables || {}; const typography = jsonData.typography || {}; const titles = jsonData.titles || {}; const metadata = jsonData.metadata || {};
const xChannel = chartUtils.schema.channel(jsonData, "x"); const yChannel = chartUtils.schema.channel(jsonData, "y"); const xField = xChannel.key; const yField = yChannel.key; const yUnit = yChannel.unit && yChannel.unit !== "none" ? yChannel.unit : "";
const rawRows = chartData.map((d, i) => ({ sourceIndex: i, category: String(d[xField] ?? ""), value: +d[yField] })).filter(d => Number.isFinite(d.value) && d.category);
const isTimeLikeField = /year|date|month|time|season|semester|quarter/i.test(String(xField || "")); const monthIndex = { 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 }; function timeKey(label) { const s = String(label || "").trim().toLowerCase(); const year = s.match(/\b(19|20)\d{2}\b/); if (year) return +year[0]; const month = monthIndex[s] || monthIndex[s.slice(0, 3)]; if (month) return month; const parsed = Date.parse(s); return Number.isFinite(parsed) ? parsed : null; }
const processedData = [...rawRows].sort((a, b) => { if (isTimeLikeField) { const ak = timeKey(a.category); const bk = timeKey(b.category); if (ak !== null && bk !== null && ak !== bk) return ak - bk; } return b.value - a.value; });
d3.select(containerSelector).html("");
const baseWidth = 1120; const rowCount = Math.max(1, processedData.length); const rowStep = Math.max(42, Math.min(58, 480 / rowCount)); const rowH = Math.max(34, Math.min(48, rowStep * 0.78)); const plotTop = 46; const baseHeight = Math.max(620, plotTop + rowStep * rowCount + 92);
const width = variables.width && variables.width > 700 ? variables.width : baseWidth; const scale = width / baseWidth; const height = Math.round(baseHeight * scale); const vbH = baseHeight;
const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", height) .attr("viewBox", `0 0 ${baseWidth} ${vbH}`) .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink");
const uid = `horizontal_bar_0_${Math.random().toString(36).slice(2, 9)}`; const defs = svg.append("defs"); const bgGradient = defs.append("linearGradient") .attr("id", `${uid}_bg`) .attr("x1", "0%").attr("y1", "0%") .attr("x2", "100%").attr("y2", "100%"); bgGradient.append("stop").attr("offset", "0%").attr("stop-color", "#ffffff"); bgGradient.append("stop").attr("offset", "62%").attr("stop-color", "#f7fbff"); bgGradient.append("stop").attr("offset", "100%").attr("stop-color", "#d9ecf8");
const barGradient = defs.append("linearGradient") .attr("id", `${uid}_bar`) .attr("x1", "0%").attr("y1", "0%") .attr("x2", "100%").attr("y2", "0%"); barGradient.append("stop").attr("offset", "0%").attr("stop-color", "#0a55ad"); barGradient.append("stop").attr("offset", "58%").attr("stop-color", "#126ec6"); barGradient.append("stop").attr("offset", "100%").attr("stop-color", "#43a9f3");
const softShadow = defs.append("filter") .attr("id", `${uid}_soft_shadow`) .attr("x", "-12%").attr("y", "-24%") .attr("width", "124%").attr("height", "148%"); softShadow.append("feDropShadow") .attr("dx", 0).attr("dy", 4) .attr("stdDeviation", 5) .attr("flood-color", "#16456e") .attr("flood-opacity", 0.11);
svg.append("rect") .attr("class", "reference-canvas") .attr("x", 0).attr("y", 0) .attr("width", baseWidth).attr("height", vbH) .attr("rx", 24).attr("fill", `url(#${uid}_bg)`) .attr("stroke", "rgba(32,70,105,0.18)");
const chart = { x: 26, y: 30, w: 714, h: vbH - 58 }; const right = { x: 770, y: 52, w: 310, h: vbH - 96 }; const iconX = chart.x + 44; const labelX = chart.x + 92; const barX = chart.x + 304; const valueTexts = processedData.map(d => formatValue(d.value)); const maxValueTextLen = d3.max(valueTexts, d => d.length) || 0; const valueFontPx = rowCount > 12 ? 14 : (maxValueTextLen > 10 ? 15 : 18); const valueColumnW = Math.min(210, Math.max(60, Math.ceil(maxValueTextLen * valueFontPx * 0.66))); const valueRightX = right.x - 22; const barW = Math.max(150, valueRightX - valueColumnW - 12 - barX);
svg.append("rect") .attr("class", "reference-chart-card") .attr("x", chart.x).attr("y", chart.y) .attr("width", chart.w).attr("height", chart.h) .attr("rx", 18) .attr("fill", "rgba(255,255,255,0.74)") .attr("stroke", "rgba(30,82,125,0.10)") .style("filter", `url(#${uid}_soft_shadow)`);
const maxValue = d3.max(processedData, d => d.value) || 1; const xScale = d3.scaleLinear() .domain([0, Math.max(maxValue, 1)]) .range([0, barW]);
function formatValue(v) { const base = chartUtils.format.autoText(v); return `${base}${yUnit ? yUnit : ""}`; }
function splitLabel(label) { const match = String(label).match(/^(.*?)\s*\(([^)]*)\)\s*$/); const primaryText = match ? match[1].trim() : String(label).trim(); const suffix = match ? `(${match[2].trim()})` : ""; const words = primaryText.split(/\s+/).filter(Boolean); if (primaryText.length > 19 && words.length > 1) { let first = ""; const rest = []; words.forEach(word => { const trial = first ? `${first} ${word}` : word; if (!first || trial.length <= 18) { first = trial; } else { rest.push(word); } }); const second = [rest.join(" "), suffix].filter(Boolean).join(" ").trim(); return [first, second]; } return [primaryText, suffix]; }
function wrapTextLines(text, maxChars, maxLines) { const words = String(text || "").split(/\s+/).filter(Boolean); const lines = []; let current = ""; words.forEach(word => { const next = current ? `${current} ${word}` : word; if (next.length > maxChars && current) { lines.push(current); current = word; } else { current = next; } }); if (current) lines.push(current); if (lines.length > maxLines) { const kept = lines.slice(0, maxLines); kept[maxLines - 1] = `${kept[maxLines - 1].replace(/\.*$/, "")}...`; return kept; } return lines; }
const rowsG = svg.append("g") .attr("class", "reference-horizontal-bar-list") .attr("data-field-x", xField) .attr("data-field-y", yField);
processedData.forEach((d, i) => { const cy = plotTop + i * rowStep + rowH / 2; const rowY = cy - rowH / 2; const row = rowsG.append("g") .attr("class", "reference-bar-row") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("data-display-value", formatValue(d.value)) .attr("data-rank", i + 1);
row.append("rect") .attr("class", "reference-row-card") .attr("x", chart.x + 20) .attr("y", rowY) .attr("width", chart.w - 46) .attr("height", rowH) .attr("rx", rowH / 2) .attr("fill", "#ffffff") .attr("stroke", "rgba(49,97,142,0.08)") .style("filter", `url(#${uid}_soft_shadow)`);
const slotR = Math.min(22, rowH * 0.46); const slot = row.append("g") .attr("class", "reference-row-icon-slot reserved-asset-slot") .attr("data-asset-slot", "row-category-icon") .attr("data-reserved-slot", "row-category-icon") .attr("data-bbox", `${iconX - slotR},${cy - slotR},${slotR * 2},${slotR * 2}`) .attr("data-anchor", `row-center:${d.category}`) .attr("data-collision-rule", "row icon slot must avoid category label, bar, value label, and canvas edge") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-asset-source-policy", "image2_asset") .attr("transform", `translate(${iconX},${cy})`);
slot.append("circle") .attr("r", slotR) .attr("fill", "#f7fbff") .attr("stroke", "#1f80dc") .attr("stroke-width", 2.2); slot.append("circle") .attr("r", slotR * 0.68) .attr("fill", "rgba(31,128,220,0.10)") .attr("stroke", "rgba(31,128,220,0.18)"); slot.append("text") .attr("class", "row-rank-neutral-marker") .attr("x", 0).attr("y", 4) .attr("text-anchor", "middle") .style("font-family", typography.label?.font_family || "Arial") .style("font-size", "10px") .style("font-weight", 800) .style("fill", "#0b52ab") .text(i + 1);
const [primary, secondary] = splitLabel(d.category); const labelFont = rowCount > 12 ? 13 : 15; row.append("text") .attr("class", "category-label") .attr("x", labelX) .attr("y", secondary ? cy - 3 : cy + 5) .attr("fill", "#092d5c") .style("font-family", typography.label?.font_family || "Arial") .style("font-size", `${labelFont}px`) .style("font-weight", 800) .text(primary); if (secondary) { row.append("text") .attr("class", "category-label-secondary") .attr("x", labelX) .attr("y", cy + 13) .attr("fill", "#64748b") .style("font-family", typography.label?.font_family || "Arial") .style("font-size", `${Math.max(10, labelFont - 2)}px`) .style("font-weight", 600) .text(secondary); }
const barH = Math.max(16, Math.min(26, rowH * 0.54)); const barY = cy - barH / 2; row.append("rect") .attr("class", "bar mark") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("data-endcap-shape", "rounded-pill") .attr("x", barX) .attr("y", barY) .attr("width", Math.max(barH, xScale(d.value))) .attr("height", barH) .attr("rx", barH / 2) .attr("fill", `url(#${uid}_bar)`);
row.append("text") .attr("class", "value-label") .attr("data-source-index", d.sourceIndex) .attr("data-category", d.category) .attr("data-value", d.value) .attr("x", valueRightX) .attr("y", cy + 6) .attr("text-anchor", "end") .attr("fill", "#0a438a") .style("font-family", typography.label?.font_family || "Arial") .style("font-size", `${valueFontPx}px`) .style("font-weight", 900) .text(formatValue(d.value)); });
const rightG = svg.append("g") .attr("class", "reference-right-panel") .attr("data-anchor", "right-safe-column") .attr("data-collision-rule", "independent right panel avoids chart rows and value labels");
const heroSlot = rightG.append("g") .attr("class", "right-hero-illustration-slot reserved-asset-slot") .attr("data-asset-slot", "right-hero-illustration") .attr("data-reserved-slot", "right-hero-illustration") .attr("data-bbox", `${right.x + 28},${right.y},${right.w - 56},170`) .attr("data-anchor", "right-panel-top") .attr("data-collision-rule", "hero slot must stay above title and away from chart rows") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-asset-source-policy", "image2_asset"); heroSlot.append("circle") .attr("cx", right.x + right.w / 2) .attr("cy", right.y + 86) .attr("r", 78) .attr("fill", "#d7ebfb"); heroSlot.append("rect") .attr("x", right.x + 70) .attr("y", right.y + 54) .attr("width", 170) .attr("height", 92) .attr("rx", 18) .attr("fill", "rgba(255,255,255,0.54)") .attr("stroke", "rgba(16,103,183,0.15)"); heroSlot.append("line") .attr("x1", right.x + 92).attr("x2", right.x + 218) .attr("y1", right.y + 126).attr("y2", right.y + 82) .attr("stroke", "rgba(10,67,138,0.42)") .attr("stroke-width", 10) .attr("stroke-linecap", "round");
const rawTitle = String(titles.main_title || metadata.title || `${yField} by ${xField}`).trim(); const titleWords = rawTitle.replace(/\bby\b/ig, "by").split(/\s+/); const byIndex = titleWords.findIndex(w => w.toLowerCase() === "by"); const titleMain = byIndex > 0 ? titleWords.slice(0, byIndex).join(" ") : rawTitle; const titleSub = byIndex > 0 ? titleWords.slice(byIndex).join(" ") : ""; const titleLines = wrapTextLines(titleMain.toUpperCase(), 16, 3); let titleY = right.y + 252; titleLines.forEach((line, i) => { rightG.append("text") .attr("class", "reference-title") .attr("x", right.x + right.w / 2) .attr("y", titleY + i * 34) .attr("text-anchor", "middle") .style("font-family", typography.title?.font_family || "Arial") .style("font-size", "30px") .style("font-weight", 900) .style("letter-spacing", "1.2px") .style("fill", "#072b5e") .text(line); }); const subY = titleY + titleLines.length * 34 + 2; rightG.append("text") .attr("class", "reference-title-subline") .attr("x", right.x + right.w / 2) .attr("y", subY) .attr("text-anchor", "middle") .style("font-family", typography.title?.font_family || "Arial") .style("font-size", "24px") .style("font-weight", 800) .style("fill", "#2b83d8") .text(titleSub || String(xField || ""));
const dividerY = subY + 42; rightG.append("line") .attr("x1", right.x + 56).attr("x2", right.x + 132) .attr("y1", dividerY).attr("y2", dividerY) .attr("stroke", "#b7ccdd").attr("stroke-width", 1.5); rightG.append("line") .attr("x1", right.x + right.w - 132).attr("x2", right.x + right.w - 56) .attr("y1", dividerY).attr("y2", dividerY) .attr("stroke", "#b7ccdd").attr("stroke-width", 1.5); const dividerSlot = rightG.append("g") .attr("class", "title-divider-icon-slot reserved-asset-slot") .attr("data-asset-slot", "title-divider-icon") .attr("data-reserved-slot", "title-divider-icon") .attr("data-bbox", `${right.x + right.w / 2 - 16},${dividerY - 16},32,32`) .attr("data-anchor", "right-panel-title-divider") .attr("data-collision-rule", "small divider slot avoids title and description text") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-asset-source-policy", "image2_asset") .attr("transform", `translate(${right.x + right.w / 2},${dividerY})`); dividerSlot.append("circle") .attr("r", 12) .attr("fill", "rgba(11,82,171,0.10)") .attr("stroke", "rgba(11,82,171,0.22)");
const description = String(titles.sub_title || metadata.description || metadata.main_insight || "").replace(/\*\*/g, ""); const descLines = wrapTextLines(description, 32, 4); descLines.forEach((line, i) => { rightG.append("text") .attr("class", "reference-description") .attr("x", right.x + right.w / 2) .attr("y", dividerY + 56 + i * 23) .attr("text-anchor", "middle") .style("font-family", typography.description?.font_family || "Arial") .style("font-size", "15px") .style("font-weight", i === descLines.length - 1 ? 700 : 500) .style("fill", i === descLines.length - 1 ? "#47753b" : "#53687d") .text(line); });
const landscape = svg.append("g") .attr("class", "bottom-landscape-decoration-slot reserved-asset-slot") .attr("data-asset-slot", "bottom-landscape-decoration") .attr("data-reserved-slot", "bottom-landscape-decoration") .attr("data-bbox", `${baseWidth * 0.56},${vbH - 84},${baseWidth * 0.40},72`) .attr("data-anchor", "bottom-right-background") .attr("data-collision-rule", "background slot must stay behind bars, value labels, and right-panel text") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-asset-source-policy", "image2_asset") .attr("opacity", 0.34); const hill = d3.area() .x(d => d[0]) .y0(vbH) .y1(d => d[1]) .curve(d3.curveBasis); landscape.append("path") .attr("d", hill([[baseWidth * 0.54, vbH - 10], [baseWidth * 0.64, vbH - 31], [baseWidth * 0.74, vbH - 24], [baseWidth * 0.84, vbH - 52], [baseWidth * 0.98, vbH - 43]])) .attr("fill", "#bcd7ec"); [0.66, 0.72, 0.88, 0.94].forEach((t, i) => { const x = baseWidth * t; const y = vbH - 18 - i * 7; landscape.append("path") .attr("d", `M${x},${y} l11,0 l-9,-12 l7,0 l-8,-14 l6,0 l-8,-16 l-8,16 l6,0 l-8,14 l7,0 l-9,12 l11,0 Z`) .attr("fill", "#95b9d5"); });
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_test", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary","secondary"], "supported_effects": ["gradient", "stroke", "radius_corner"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // Block 1: Configuration & Data Extraction // --------------------------------------------------------------------- const jsonData = data; const chartData = jsonData.data.data; const variables = jsonData.variables || {}; const typography = { title: { font_family: "Arial", font_size: "28px", font_weight: 700, ...((jsonData.typography || {}).title || {}) }, label: { font_family: "Arial", font_size: "16px", font_weight: 500, ...((jsonData.typography || {}).label || {}) }, description: { font_family: "Arial", font_size: "16px", font_weight: 500, ...((jsonData.typography || {}).description || {}) }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400, ...((jsonData.typography || {}).annotation || {}) } }; const colors = { text_color: "#FFFFFF", background_color: "#0A3B39", other: { primary: "#83C341", secondary: "#83C341", ...(jsonData.colors || {}).other }, ...(jsonData.colors || {}) }; const images = jsonData.images || { field: {}, other: {} }; const dataColumns = chartUtils.schema.columns(jsonData);
// Removed default fallback strings for field names and column titles const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField1 = chartUtils.schema.channel(jsonData, "y").key; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key;
let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : (chartUtils.schema.channel(jsonData, "y").unit || ""); let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none" ? "" : (chartUtils.schema.channel(jsonData, "y2").unit || "");
const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key;
// Early exit or error if critical fields are not defined (optional, but good practice) if (!dimensionField || !valueField1 || !valueField2) { console.error("Critical data fields (dimensionField, valueField1, or valueField2) are not defined in dataColumns. Cannot render chart."); d3.select(containerSelector).html("<p style='color:red;'>Error: Chart configuration incomplete. Required data fields missing.</p>"); return null; // Or throw new Error(...) }
// Block 2: SVG Container Setup // --------------------------------------------------------------------- d3.select(containerSelector).html(""); const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", variables.height || 600) .attr("viewBox", `0 0 ${variables.width || 800} ${variables.height || 600}`) .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink");
// Block 3: Global Utilities & Helper Functions // --------------------------------------------------------------------- const tempTextMeasureGroup = svg.append("g").attr("visibility", "hidden").attr("id", "tempTextMeasureGroup");
const estimateTextWidth = (text, fontConfig, dynamicFontSize = null) => chartUtils.text.measure(tempTextMeasureGroup, text, { fontFamily: fontConfig.font_family, fontSize: dynamicFontSize || fontConfig.font_size, fontWeight: fontConfig.font_weight }).width;
function getWrappedTextLines(textContent, availableWidth, fontConfig) { const words = (textContent || "").trim().split(/\s+/).filter(w => w !== ""); // Handles undefined textContent gracefully const lines = []; const fontSizeValue = parseFloat(fontConfig.font_size); const lineHeight = fontSizeValue * 1.2;
if (words.length === 0) return { linesArray: [], numLines: 0, lineHeight: lineHeight };
const breakSingleWord = (word) => { let currentWordPart = ""; const wordLines = []; for (let char of word) { if (estimateTextWidth(currentWordPart + char, fontConfig) > availableWidth && currentWordPart !== "") { wordLines.push(currentWordPart); currentWordPart = char; } else { currentWordPart += char; } } if (currentWordPart !== "") wordLines.push(currentWordPart); return wordLines.length > 0 ? wordLines : [word]; };
if (words.length === 1) { lines.push(...(estimateTextWidth(words[0], fontConfig) > availableWidth ? breakSingleWord(words[0]) : [words[0]])); return { linesArray: lines.filter(l => l), numLines: lines.filter(l => l).length, lineHeight: lineHeight }; } let currentLine = words[0]; if (estimateTextWidth(currentLine, fontConfig) > availableWidth) { const brokenFirstWord = breakSingleWord(currentLine); lines.push(...brokenFirstWord.slice(0, -1)); currentLine = brokenFirstWord.length > 0 ? brokenFirstWord[brokenFirstWord.length - 1] : ""; }
for (let i = 1; i < words.length; i++) { const word = words[i]; if (estimateTextWidth(word, fontConfig) > availableWidth) { if (currentLine !== "") lines.push(currentLine); lines.push(...breakSingleWord(word)); currentLine = ""; continue; } const testLine = currentLine === "" ? word : currentLine + " " + word; if (estimateTextWidth(testLine, fontConfig) > availableWidth && currentLine !== "") { lines.push(currentLine); currentLine = word; } else { currentLine = testLine; } } if (currentLine !== "") { lines.push(...(estimateTextWidth(currentLine, fontConfig) > availableWidth ? breakSingleWord(currentLine) : [currentLine])); } return { linesArray: lines.filter(l => l), numLines: lines.filter(l => l).length, lineHeight: lineHeight }; }
const getPrimaryColor = (variation = "default") => { const base = colorResolver.other("primary").value; if (variation === "darker") return colorResolver.variant(base, { mode: "darker", amount: 0.3 }).toString(); if (variation === "brighter") return colorResolver.variant(base, { mode: "brighter", amount: 0.5 }).toString(); if (variation === "stroke") return colorResolver.variant(base, { mode: "brighter", amount: 3 }).toString(); return base; }; const getSecondaryColor = () => colorResolver.other("secondary").value;
// Block 4: Core Chart Dimensions & Layout Calculation // --------------------------------------------------------------------- const width = variables.width || 800; const height = variables.height || 600; const flagWidth = 30; const flagHeight = 30; const textPadding = 5; const minFontSize = 8; const defaultLabelFontSize = parseFloat(typography.label.font_size);
let maxDimLabelWidth = 0; chartData.forEach(d => { // Ensure d[dimensionField] is treated as a string for consistent measurement maxDimLabelWidth = Math.max(maxDimLabelWidth, estimateTextWidth(String(d[dimensionField] || "").toUpperCase(), typography.label)); });
const maxAllowedLabelSpace = width * 0.15; let finalDimLabelFontSize = defaultLabelFontSize; if (maxDimLabelWidth > maxAllowedLabelSpace) { const scaleFactor = maxAllowedLabelSpace / maxDimLabelWidth; finalDimLabelFontSize = Math.max(minFontSize, defaultLabelFontSize * scaleFactor); maxDimLabelWidth = 0; chartData.forEach(d => { maxDimLabelWidth = Math.max(maxDimLabelWidth, estimateTextWidth(String(d[dimensionField] || "").toUpperCase(), typography.label, `${finalDimLabelFontSize}px`)); }); } const margin = { top: 100, right: 5, bottom: 40, left: maxDimLabelWidth + textPadding + flagWidth + textPadding + 5 };
const leftColumnRatio = 0.85; const rightColumnRatio = 0.15; const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; const barChartWidth = innerWidth * leftColumnRatio; const circleChartWidth = innerWidth * rightColumnRatio;
// Block 5: Data Preprocessing // --------------------------------------------------------------------- const sortedData = [...chartData].sort((a, b) => (b[valueField1] || 0) - (a[valueField1] || 0)); // Added fallback for sorting const sortedDimensions = sortedData.map(d => d[dimensionField]);
// Block 6: Scale Definition // --------------------------------------------------------------------- const barPadding = 0.2; const yScale = d3.scaleBand() .domain(sortedDimensions) // If dimensionField was undefined, sortedDimensions might be array of undefineds .range([0, innerHeight]) .padding(barPadding);
const xScale = d3.scaleLinear() // Added fallback for max calculation in case valueField1 is missing or data is malformed .domain([0, d3.max(sortedData, d => +(d[valueField1] || 0)) * 1.05 || 1]) // Ensure domain is valid .range([0, barChartWidth]);
const maxValue2 = d3.max(sortedData, d => +(d[valueField2] || 0)); const minRadius = yScale.bandwidth() * 0.3; // yScale.bandwidth() could be 0 if sortedDimensions is empty const maxRadius = Math.min(yScale.bandwidth() * 1.0 || 20, circleChartWidth * 0.5 || 20); // Added fallback for bandwidth const radiusScale = d3.scaleSqrt() .domain([0, maxValue2 || 0]) .range([minRadius || 5, maxRadius || 20]); // Added fallback for radii
// Block 7: SVG Definitions (Defs) - Gradients, Filters, Patterns // --------------------------------------------------------------------- const defs = svg.append("defs"); const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%").attr("y1", "0%").attr("x2", "100%").attr("y2", "0%"); gradient.append("stop").attr("offset", "0%").attr("stop-color", getPrimaryColor("darker")); gradient.append("stop").attr("offset", "100%").attr("stop-color", getPrimaryColor("brighter"));
// Block 8: Drawing Chart Titles & Headers (Column Titles) // --------------------------------------------------------------------- // columnTitle1 and columnTitle2 might be undefined. getWrappedTextLines handles this. const titleFontConfig = typography.description; const titleBottomPadding = 5; const desiredBaselineOfLastLine = margin.top - titleBottomPadding;
const leftTitleAvailableWidth = innerWidth * 0.6; const leftTitleXPos = margin.left; const wrappedLeftTitle = getWrappedTextLines(columnTitle1, leftTitleAvailableWidth, titleFontConfig); if (wrappedLeftTitle.numLines > 0) { const initialYLeft = desiredBaselineOfLastLine - (wrappedLeftTitle.numLines - 1) * wrappedLeftTitle.lineHeight; const leftTitleText = svg.append("text") .attr("x", leftTitleXPos).attr("y", initialYLeft) .attr("text-anchor", "start") .style("font-family", titleFontConfig.font_family).style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight).style("fill", colorResolver.text({ fallback: "#333333" }).value); wrappedLeftTitle.linesArray.forEach((line, i) => { leftTitleText.append("tspan").attr("x", leftTitleXPos).attr("dy", i === 0 ? 0 : wrappedLeftTitle.lineHeight).text(line); }); }
const rightTitleAvailableWidth = innerWidth * 0.4; const rightTitleXPos = margin.left + innerWidth; const wrappedRightTitle = getWrappedTextLines(columnTitle2, rightTitleAvailableWidth, titleFontConfig); if (wrappedRightTitle.numLines > 0) { const initialYRight = desiredBaselineOfLastLine - (wrappedRightTitle.numLines - 1) * wrappedRightTitle.lineHeight; const rightTitleText = svg.append("text") .attr("x", rightTitleXPos).attr("y", initialYRight) .attr("text-anchor", "end") .style("font-family", titleFontConfig.font_family).style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight).style("fill", colorResolver.text({ fallback: "#333333" }).value); wrappedRightTitle.linesArray.forEach((line, i) => { rightTitleText.append("tspan").attr("x", rightTitleXPos).attr("dy", i === 0 ? 0 : wrappedRightTitle.lineHeight).text(line); }); }
// Block 9: Main Chart Rendering Loop // --------------------------------------------------------------------- const g = svg.append("g").attr("transform", `translate(${margin.left}, ${margin.top})`);
sortedData.forEach((dataPoint, index) => { const dimension = dataPoint[dimensionField]; // Might be undefined if dimensionField was not found const barHeight = yScale.bandwidth(); // Might be 0 or NaN if domain was empty/problematic const y = yScale(dimension); // If y is undefined, centerY will be NaN. Operations using it will likely fail silently for SVG. const centerY = y + barHeight / 2; const barWidthValue = Math.max(0, xScale(+(dataPoint[valueField1] || 0))); // Added fallback
// --- Dimension Label & Icon --- const dimLabelX = -(flagWidth + textPadding + 5); const iconX = -flagWidth - 5;
g.append("text") .attr("x", dimLabelX).attr("y", centerY).attr("dy", "0.35em") .attr("text-anchor", "end") .style("font-family", typography.label.font_family).style("font-size", `${finalDimLabelFontSize}px`) .style("font-weight", typography.label.font_weight).style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(String(dimension || "").toUpperCase()); // Handle undefined dimension for text
const iconGroup = g.append("g").attr("transform", `translate(${iconX}, ${centerY - flagHeight / 2})`); // Ensure dimension is a string for image key lookup, or provide a fallback const imageKey = String(dimension || `__undefined_key_${index}__`); if (images.field && images.field[imageKey]) { iconGroup.append("image") .attr("x", 0).attr("y", 0).attr("width", flagWidth).attr("height", flagHeight) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xlink:href", images.field[imageKey]); } else { iconGroup.append("rect") .attr("x", 0).attr("y", 0).attr("width", flagWidth).attr("height", flagHeight) .attr("fill", getPrimaryColor("stroke")).attr("opacity", 0.3); }
// --- Bar Element --- if (typeof y === 'number' && barHeight > 0) { // Add check to prevent drawing if y or barHeight is invalid g.append("rect") .attr("x", 0).attr("y", y) .attr("width", barWidthValue).attr("height", barHeight) .attr("fill", "url(#bar-gradient)") .attr("rx", barHeight / 4).attr("ry", barHeight / 4) .attr("opacity", 0.9);
// --- Bar Value Label --- const valueLabelText1 = `${chartUtils.format.scaledText(+(dataPoint[valueField1] || 0))}${valueUnit1}`; // Added fallback const dynamicValueLabelFontSize = `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`; const currentBarValueLabelWidth = estimateTextWidth(valueLabelText1, typography.annotation, dynamicValueLabelFontSize); let valueLabel1XPos, valueLabel1Anchor, valueLabel1Fill; const internalPadding = 10; const externalPadding = 5; if (barWidthValue >= currentBarValueLabelWidth + internalPadding * 2) { valueLabel1XPos = internalPadding; valueLabel1Anchor = "start"; valueLabel1Fill = "#FFFFFF"; } else { valueLabel1XPos = barWidthValue + externalPadding; valueLabel1Anchor = "start"; valueLabel1Fill = colorResolver.text({ fallback: "#333333" }).value; } g.append("text") .attr("x", valueLabel1XPos).attr("y", centerY).attr("dy", "0.35em") .attr("text-anchor", valueLabel1Anchor) .style("font-family", typography.annotation.font_family).style("font-size", dynamicValueLabelFontSize) .style("font-weight", typography.annotation.font_weight).style("fill", valueLabel1Fill) .text(valueLabelText1); }
// --- Circle Element --- const circleRadiusValue = radiusScale(+(dataPoint[valueField2] || 0)); // Added fallback if (typeof centerY === 'number' && typeof circleRadiusValue === 'number' && circleRadiusValue >= 0) { // Add check g.append("circle") .attr("cx", barChartWidth + circleChartWidth / 2).attr("cy", centerY) .attr("r", circleRadiusValue) .attr("fill", getSecondaryColor()) .attr("opacity", 0.6);
// --- Circle Value Label --- const valueLabelText2 = `${chartUtils.format.scaledText(+(dataPoint[valueField2] || 0))}${valueUnit2}`; // Added fallback const dynamicCircleLabelFontSize = `${Math.min(20, Math.max(barHeight * 0.6 || 10, parseFloat(typography.annotation.font_size)))}px`; // Fallback for barHeight
g.append("text") .attr("x", barChartWidth + circleChartWidth / 2).attr("y", centerY).attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family).style("font-size", dynamicCircleLabelFontSize) .style("font-weight", typography.annotation.font_weight).style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(valueLabelText2); } });
// Block 10: Cleanup // --------------------------------------------------------------------- tempTextMeasureGroup.remove();
// Block 11: Return SVG Node // --------------------------------------------------------------------- return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_0_weilai", "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[3, 20], [0, 100000]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": [], "supported_effects": ["gradient", "opacity"], "min_height": 300, "min_width": 300, "background": "light", "icon_mark": "none", "icon_label": "none", "has_x_axis": "yes", "has_y_axis": "yes"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); const jsonData = data; const chartData = jsonData.data.data; const variables = jsonData.variables || {}; const typography = jsonData.typography || { title: { font_family: "Arial", font_size: "18px", font_weight: "bold" }, label: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, description: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } };
d3.select(containerSelector).html("");
const width = Math.max(520, +(variables.width || 600)); const height = Math.max(430, +(variables.height || 560)); const xField = chartUtils.schema.channel(jsonData, "x").key || "period"; const yField = chartUtils.schema.channel(jsonData, "y").key || "value"; const yChannel = chartUtils.schema.channel(jsonData, "y") || {}; const rawUnit = yChannel.unit && yChannel.unit !== "none" ? yChannel.unit : ""; const displayUnit = rawUnit === "$" ? "USD" : rawUnit; const processedData = chartData.map((d, index) => ({ category: d[xField], value: +d[yField], index })).filter(d => Number.isFinite(d.value));
const n = Math.max(1, processedData.length); const cardX = 14; const cardY = 16; const cardW = width - cardX * 2; const cardH = height - cardY * 2; const plotTop = n > 7 ? 48 : 72; const axisH = 82; const plotBottom = cardH - axisH; const stackedRowHeader = n <= 5; const iconCx = cardX + (stackedRowHeader ? 62 : 44); const iconR = n > 7 ? 12 : (stackedRowHeader ? 28 : 18); const labelX = stackedRowHeader ? iconCx : cardX + (n > 7 ? 68 : 76); const plotX = cardX + Math.min(235, Math.max(150, cardW * (n > 7 ? 0.34 : 0.28))); const valuePad = n > 7 ? 52 : 68; const plotW = Math.max(120, cardX + cardW - plotX - valuePad); const labelMaxWidth = Math.max(60, plotX - labelX - 14); const maxValue = d3.max(processedData, d => d.value) || 1;
const yScale = d3.scaleBand() .domain(processedData.map(d => d.category)) .range([plotTop, plotBottom]) .padding(n > 7 ? 0.25 : 0.38); const xScale = d3.scaleLinear() .domain([0, maxValue]) .range([0, plotW]) .nice();
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");
const safeId = `weilai-${Math.random().toString(36).slice(2)}`; const defs = svg.append("defs"); const shadow = defs.append("filter") .attr("id", `${safeId}-card-shadow`) .attr("x", "-8%") .attr("y", "-8%") .attr("width", "116%") .attr("height", "116%"); shadow.append("feDropShadow") .attr("dx", 0) .attr("dy", 10) .attr("stdDeviation", 10) .attr("flood-color", "#23415C") .attr("flood-opacity", 0.10);
const gridTicks = xScale.ticks(5); const axisY = cardY + plotBottom + 28; const plotTopAbs = cardY + plotTop; const plotBottomAbs = cardY + plotBottom; const plotXAbs = plotX;
const card = svg.append("g") .attr("class", "weilai-chart-card") .attr("data-role", "chart-card") .attr("data-reference-relationship", "white rounded card contains row icon slots, category labels, bars, values, and x-axis");
card.append("rect") .attr("x", cardX) .attr("y", cardY) .attr("width", cardW) .attr("height", cardH) .attr("rx", 14) .attr("fill", "#FFFFFF") .attr("stroke", "#E5EEF6") .attr("stroke-width", 1.2) .attr("filter", `url(#${safeId}-card-shadow)`);
card.selectAll(".weilai-gridline") .data(gridTicks) .enter() .append("line") .attr("class", "weilai-gridline") .attr("x1", d => plotXAbs + xScale(d)) .attr("x2", d => plotXAbs + xScale(d)) .attr("y1", plotTopAbs - 4) .attr("y2", plotBottomAbs + 10) .attr("stroke", "#EAF0F6") .attr("stroke-width", 1);
card.append("line") .attr("class", "weilai-baseline") .attr("data-reference-relationship", "flat left bar baseline flush with x-axis origin") .attr("x1", plotXAbs) .attr("x2", plotXAbs) .attr("y1", plotTopAbs - 6) .attr("y2", plotBottomAbs + 12) .attr("stroke", "#D5E1EC") .attr("stroke-width", 1.2);
const row = card.selectAll(".weilai-row") .data(processedData) .enter() .append("g") .attr("class", "weilai-row") .attr("data-category", d => d.category) .attr("data-value", d => d.value) .attr("transform", d => `translate(0, ${cardY + yScale(d.category) + yScale.bandwidth() / 2})`);
row.append("circle") .attr("class", "reserved-asset-slot weilai-row-icon-slot") .attr("data-asset-slot", "weilai_row_icon_slot") .attr("data-slot-policy", "retrieval_or_image2_asset") .attr("data-asset-source-policy", "retrieval_or_image2_asset_per_category") .attr("data-anchor", "row-center-left-of-category-label") .attr("data-collision-rule", "stay inside chart card row header column and share row centerline with bar") .attr("data-bbox-policy", "cx cy and r define circular icon slot bbox") .attr("data-mask-policy", "downstream asset may replace only inside this circle") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-category", d => d.category) .attr("cx", iconCx) .attr("cy", 0) .attr("r", iconR) .attr("fill", (d, i) => i % 2 ? "#F1FBF8" : "#EEF5FF") .attr("stroke", (d, i) => i % 2 ? "#8BD7C0" : "#BBD2F5") .attr("stroke-width", 1.4) .attr("stroke-dasharray", "4 3");
row.append("circle") .attr("class", "weilai-row-icon-neutral-anchor") .attr("cx", iconCx) .attr("cy", 0) .attr("r", Math.max(2.8, iconR * 0.16)) .attr("fill", "#0A8B72") .attr("opacity", 0.28) .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true");
row.append("text") .attr("class", "weilai-category-label") .attr("x", labelX) .attr("y", stackedRowHeader ? iconR + 27 : (n > 7 ? -2 : -5)) .attr("text-anchor", stackedRowHeader ? "middle" : "start") .attr("font-family", typography.label.font_family || "Arial, Helvetica, sans-serif") .attr("font-size", n > 7 ? 11 : (stackedRowHeader ? 16 : 14)) .attr("font-weight", 700) .attr("fill", "#0F2F55") .attr("letter-spacing", 0) .attr("textLength", d => { const fontSize = n > 7 ? 11 : (stackedRowHeader ? 16 : 14); const maxWidth = stackedRowHeader ? Math.max(70, iconR * 2.7) : labelMaxWidth; return estimateTextWidth(String(d.category), fontSize) > maxWidth ? maxWidth : null; }) .attr("lengthAdjust", "spacingAndGlyphs") .text(d => String(d.category));
row.append("path") .attr("class", "bar weilai-bar") .attr("data-reference-end-shape", "flat-left-baseline-rounded-right-value-edge") .attr("data-category", d => d.category) .attr("data-value", d => d.value) .attr("d", d => rightRoundedBarPath(plotXAbs, -yScale.bandwidth() / 2, Math.max(2, xScale(d.value)), yScale.bandwidth(), Math.min(yScale.bandwidth() / 2, 9))) .attr("fill", (d, i) => i === 0 ? "#0C4FC3" : (i === 1 ? "#2F78F4" : "#2B8AF5")) .attr("opacity", 0.98);
row.each(function(d) { const g = d3.select(this); const endX = plotXAbs + xScale(d.value); const outsideX = endX + 12; const clamped = outsideX > cardX + cardW - 38; const valueX = clamped ? cardX + cardW - 28 : outsideX; const anchor = clamped ? "end" : "start"; g.append("text") .attr("class", "weilai-value-label") .attr("x", valueX) .attr("y", displayUnit ? -4 : 4) .attr("text-anchor", anchor) .attr("font-family", typography.label.font_family || "Arial, Helvetica, sans-serif") .attr("font-size", n > 7 ? 11 : 22) .attr("font-weight", 800) .attr("fill", "#0B56D0") .attr("letter-spacing", 0) .text(chartUtils.format.autoText(d.value)); if (displayUnit) { g.append("text") .attr("class", "weilai-value-unit") .attr("x", valueX) .attr("y", n > 7 ? 9 : 13) .attr("text-anchor", anchor) .attr("font-family", typography.label.font_family || "Arial, Helvetica, sans-serif") .attr("font-size", n > 7 ? 7 : 13) .attr("font-weight", 700) .attr("fill", "#7690AA") .attr("letter-spacing", 0) .text(displayUnit); } });
const axis = card.append("g") .attr("class", "weilai-x-axis") .attr("data-reference-relationship", "independent bottom axis inside chart card");
axis.selectAll(".weilai-tick-label") .data(gridTicks) .enter() .append("text") .attr("class", "weilai-tick-label") .attr("x", d => plotXAbs + xScale(d)) .attr("y", axisY) .attr("text-anchor", "middle") .attr("font-family", typography.label.font_family || "Arial, Helvetica, sans-serif") .attr("font-size", n > 7 ? 8 : 10) .attr("font-weight", 500) .attr("fill", "#8A9BAE") .attr("letter-spacing", 0) .text(d => chartUtils.format.autoText(d));
axis.append("text") .attr("class", "weilai-axis-title") .attr("x", plotXAbs + plotW / 2) .attr("y", axisY + (n > 7 ? 24 : 30)) .attr("text-anchor", "middle") .attr("font-family", typography.label.font_family || "Arial, Helvetica, sans-serif") .attr("font-size", n > 7 ? 8 : 10) .attr("font-weight", 800) .attr("fill", "#526C86") .attr("letter-spacing", 0) .text(`${axisLabelBase()}${displayUnit ? ` (${displayUnit})` : ""}`.toUpperCase());
function rightRoundedBarPath(x, y, w, h, r) { const radius = Math.min(r, h / 2, Math.max(0, w)); if (w <= radius) { return `M${x},${y} H${x + w} V${y + h} H${x} Z`; } return [ `M${x},${y}`, `H${x + w - radius}`, `Q${x + w},${y} ${x + w},${y + radius}`, `V${y + h - radius}`, `Q${x + w},${y + h} ${x + w - radius},${y + h}`, `H${x}`, "Z" ].join(" "); }
function humanize(value) { return String(value || "Value") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/[_-]+/g, " ") .trim(); }
function axisLabelBase() { const base = humanize(yField); if (!displayUnit) { return base; } return base.replace(new RegExp(`\\s*${escapeRegExp(displayUnit)}$`, "i"), "").trim() || base; }
function escapeRegExp(value) { return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); }
function estimateTextWidth(value, fontSize) { return String(value || "").length * fontSize * 0.58; }
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_1", "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[3, 20], [0, 100]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary", "secondary", "background"], "supported_effects": ["gradient", "opacity"], "min_height": 600, "min_width": 800, "background": "light", "icon_mark": "none", "icon_label": "none", "has_x_axis": "yes", "has_y_axis": "yes"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const jsonData = data || {}; const colorResolver = chartUtils.color.resolver(jsonData); const chartData = (jsonData.data && jsonData.data.data) || []; const variables = jsonData.variables || {}; const typography = jsonData.typography || {}; const xChannel = chartUtils.schema.channel(jsonData, "x", { fallbackIndex: 0 }); const yChannel = chartUtils.schema.channel(jsonData, "y", { fallbackIndex: 1 }); const xField = xChannel.key || (xChannel.raw && xChannel.raw.name) || "category"; const yField = yChannel.key || (yChannel.raw && yChannel.raw.name) || "value"; const yUnit = yChannel.unit && yChannel.unit !== "none" ? yChannel.unit : "";
d3.select(containerSelector).html("");
const width = Math.max(760, Number(variables.width) || 600); const validRowCount = chartData.filter(d => Number.isFinite(Number(d[yField])) && readable(d[xField])).length || 1; const denseHeight = validRowCount > 12 ? Math.min(560, Math.max(430, validRowCount * 34)) : 390; const height = denseHeight; const fontFamily = (typography.label && typography.label.font_family) || "Arial, Helvetica, sans-serif"; const textStrong = "#111E3B"; const rose = "#D9476B"; const roseDark = "#CC3E63"; const roseSoft = "#F8CDD4"; const bandFill = "#FFF2F2"; const baselineColor = "#D8B8BC";
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", "horizontal-bar-chart-1-reference-grid");
const safeId = chartUtils.random.value(jsonData, "horizontal_bar_chart_1").toString(36).slice(2, 10); const defs = svg.append("defs"); const barGradientId = `hbar1-rose-gradient-${safeId}`; defs.append("linearGradient") .attr("id", barGradientId) .attr("x1", "0%") .attr("x2", "100%") .attr("y1", "0%") .attr("y2", "0%") .selectAll("stop") .data([ { offset: "0%", color: "#F6AAB8" }, { offset: "62%", color: rose }, { offset: "100%", color: roseDark } ]) .enter() .append("stop") .attr("offset", d => d.offset) .attr("stop-color", d => d.color);
function message(text) { svg.append("text") .attr("x", width / 2) .attr("y", height / 2) .attr("text-anchor", "middle") .style("font-family", fontFamily) .style("font-size", "16px") .style("fill", textStrong) .text(text); return svg.node(); }
function readable(value) { return String(value == null ? "" : value) .replace(/_/g, " ") .replace(/\s+/g, " ") .trim(); }
function parseTemporalRank(value) { const text = String(value == null ? "" : 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 }; const seasons = { winter: 1, spring: 2, summer: 3, fall: 4, autumn: 4 }; if (months[lower] != null) return months[lower]; let match = text.match(/^(\d{1,2}):(\d{2})(?::(\d{2}))?$/); if (match) return Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3] || 0); 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) || text.match(/^(-?\d{4})\s+Q([1-4])$/i); if (match && text.toUpperCase().startsWith("Q")) return Number(match[2]) * 10 + Number(match[1]); if (match) return Number(match[1]) * 10 + Number(match[2]); match = text.match(/^(winter|spring|summer|fall|autumn)\s+(-?\d{4})$/i); if (match) return Number(match[2]) * 10 + seasons[match[1].toLowerCase()]; match = text.match(/^(-?\d{4})\s+(winter|spring|summer|fall|autumn)$/i); if (match) return Number(match[1]) * 10 + seasons[match[2].toLowerCase()]; return NaN; }
function formatValue(value) { const formatted = chartUtils.format.autoText(Number(value)); if (!yUnit) return formatted; if (yUnit === "%") return `${formatted}%`; if (yUnit.startsWith("$")) return `${formatted} ${yUnit}`; return `${formatted} ${yUnit}`; }
function truncate(text, maxChars) { const value = readable(text); if (value.length <= maxChars) return value; return `${value.slice(0, Math.max(1, maxChars - 3)).trim()}...`; }
const rows = chartData .map((d, index) => ({ category: readable(d[xField]), rawCategory: d[xField], value: Number(d[yField]), firstIndex: index })) .filter(d => d.category && Number.isFinite(d.value));
if (!rows.length) return message("No valid horizontal bar data");
rows.forEach(d => { d.temporalRank = parseTemporalRank(d.rawCategory); }); const rawColumn = xChannel.raw || {}; const allTemporal = rawColumn.data_type === "temporal" || rows.every(d => Number.isFinite(d.temporalRank)); rows.sort((a, b) => { if (allTemporal) return d3.ascending(a.temporalRank, b.temporalRank) || d3.ascending(a.firstIndex, b.firstIndex); return d3.descending(a.value, b.value) || d3.ascending(a.firstIndex, b.firstIndex); });
const maxValue = Math.max(0, d3.max(rows, d => d.value) || 0); const rowCount = rows.length; const top = 12; const bottom = 24; const rowGap = rowCount > 12 ? 3 : 5; const availableH = height - top - bottom; const rowStep = availableH / rowCount; const bandH = Math.max(24, Math.min(rowStep - rowGap, 38)); const barH = Math.max(16, Math.min(bandH * 0.62, 26)); const iconR = Math.max(9, Math.min(bandH * 0.31, 18)); const iconX = width * 0.058; const labelX = width * 0.115; const baselineX = width * 0.318; const valueReserve = Math.max(76, width * 0.11); const rightSafeStart = width * 0.805; const barMaxW = Math.max(120, rightSafeStart - baselineX - valueReserve); const labelMaxWidth = Math.max(86, baselineX - labelX - 18); const labelFont = Math.max(11, Math.min(16, rowStep * 0.34)); const valueFont = Math.max(12, Math.min(18, rowStep * 0.38));
svg.append("rect") .attr("class", "chart-local-bg") .attr("x", 0) .attr("y", 0) .attr("width", width) .attr("height", height) .attr("fill", "transparent");
const slotX = width * 0.735; const slotY = Math.max(top + rowStep * 2.35, height * 0.32); const slotW = width - slotX - 24; const slotH = height - slotY - 8; const slot = svg.append("g") .attr("class", "reserved-asset-slot hbar1-right-growth-illustration-slot") .attr("data-asset-slot", "right-growth-illustration") .attr("data-reserved-slot", "right_growth_illustration_slot") .attr("data-slot-policy", "image2_asset") .attr("data-anchor", "right-chart-safe-area-below-header-callout") .attr("data-collision-rule", "avoid bars value-labels category-labels title subtitle and header-callout") .attr("data-bbox", `${slotX.toFixed(1)},${slotY.toFixed(1)},${slotW.toFixed(1)},${slotH.toFixed(1)}`) .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true"); slot.append("rect") .attr("class", "reserved-slot-bbox") .attr("x", slotX) .attr("y", slotY) .attr("width", slotW) .attr("height", slotH) .attr("rx", 28) .attr("fill", "#F8D7DD") .attr("opacity", 0.18) .attr("stroke", "#E78EA1") .attr("stroke-width", 1.1) .attr("stroke-dasharray", "5 7"); slot.append("circle") .attr("class", "reserved-slot-anchor") .attr("cx", slotX + slotW * 0.64) .attr("cy", slotY + slotH * 0.52) .attr("r", Math.max(8, Math.min(18, slotW * 0.08))) .attr("fill", rose) .attr("opacity", 0.16); slot.append("path") .attr("class", "reserved-slot-mask-hint") .attr("d", `M${slotX + slotW * 0.16},${slotY + slotH * 0.64} L${slotX + slotW * 0.44},${slotY + slotH * 0.34} L${slotX + slotW * 0.64},${slotY + slotH * 0.46} L${slotX + slotW * 0.86},${slotY + slotH * 0.17}`) .attr("fill", "none") .attr("stroke", "#F5BE49") .attr("stroke-width", Math.max(2.5, width * 0.008)) .attr("stroke-linecap", "round") .attr("stroke-linejoin", "round") .attr("opacity", 0.32);
svg.append("line") .attr("class", "bar-origin-baseline") .attr("x1", baselineX) .attr("x2", baselineX) .attr("y1", top + rowStep * 0.08) .attr("y2", height - bottom - rowStep * 0.08) .attr("stroke", baselineColor) .attr("stroke-width", 1.1);
const row = svg.selectAll(".hbar1-row") .data(rows) .enter() .append("g") .attr("class", "hbar1-row") .attr("data-category", d => d.category) .attr("data-value", d => d.value) .attr("transform", (d, i) => `translate(0, ${top + i * rowStep})`);
row.append("rect") .attr("class", "row-band") .attr("x", Math.max(8, iconX - iconR - 5)) .attr("y", (rowStep - bandH) / 2) .attr("width", Math.max(70, rightSafeStart - Math.max(8, iconX - iconR - 5))) .attr("height", bandH) .attr("rx", bandH / 2) .attr("fill", bandFill) .attr("opacity", (d, i) => i % 2 === 0 ? 0.74 : 0.58);
const icon = row.append("g") .attr("class", "reserved-asset-slot hbar1-platform-icon-slot") .attr("data-asset-slot", "platform-icon") .attr("data-reserved-slot", d => `platform_icon_slot_${d.category.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "") || "category"}`) .attr("data-slot-policy", "image2_asset") .attr("data-anchor", "row-centerline") .attr("data-collision-rule", "inside label column; avoid category labels baseline and bars") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-bbox", () => `${(iconX - iconR).toFixed(1)},${((rowStep - iconR * 2) / 2).toFixed(1)},${(iconR * 2).toFixed(1)},${(iconR * 2).toFixed(1)}`);
icon.append("circle") .attr("class", "platform-icon-slot-ring") .attr("cx", iconX) .attr("cy", rowStep / 2) .attr("r", iconR) .attr("fill", "#FFFFFF") .attr("stroke", "#F1B6C1") .attr("stroke-width", 1.5);
icon.append("circle") .attr("class", "platform-icon-neutral-placeholder") .attr("cx", iconX) .attr("cy", rowStep / 2) .attr("r", iconR * 0.72) .attr("fill", (d, i) => d3.interpolateRgb(rose, "#4BA3E3")(Math.min(0.82, i / Math.max(1, rowCount - 1)))) .attr("opacity", 0.24);
icon.append("text") .attr("x", iconX) .attr("y", rowStep / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", fontFamily) .style("font-size", `${Math.max(8, iconR * 0.62)}px`) .style("font-weight", "800") .style("fill", "#FFFFFF") .style("opacity", 0.72) .text(d => d.category.charAt(0).toUpperCase());
row.append("text") .attr("class", "category-label") .attr("x", labelX) .attr("y", rowStep / 2) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("font-family", fontFamily) .style("font-size", `${labelFont}px`) .style("font-weight", "800") .style("fill", textStrong) .attr("textLength", d => { const estimated = d.category.length * labelFont * 0.56; return estimated > labelMaxWidth ? labelMaxWidth : null; }) .attr("lengthAdjust", d => { const estimated = d.category.length * labelFont * 0.56; return estimated > labelMaxWidth ? "spacingAndGlyphs" : null; }) .text(d => d.category);
row.append("rect") .attr("class", "bar") .attr("x", baselineX + 4) .attr("y", (rowStep - barH) / 2) .attr("height", barH) .attr("width", d => Math.max(barH, (maxValue > 0 ? d.value / maxValue : 0) * barMaxW)) .attr("rx", barH / 2) .attr("ry", barH / 2) .attr("fill", `url(#${barGradientId})`) .attr("opacity", (d, i) => Math.max(0.42, 1 - i * 0.055));
row.append("text") .attr("class", "value-label") .attr("x", d => Math.min(width - 22, baselineX + 4 + Math.max(barH, (maxValue > 0 ? d.value / maxValue : 0) * barMaxW) + 14)) .attr("y", rowStep / 2) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("font-family", fontFamily) .style("font-size", `${valueFont}px`) .style("font-weight", "900") .style("fill", roseDark) .text(d => formatValue(d.value));
const dots = svg.append("g") .attr("class", "hbar1-decorative-dot-grid") .attr("aria-hidden", "true") .attr("opacity", 0.42); const dotStartX = width - 52; const dotStartY = Math.max(28, height * 0.18); d3.range(0, 6).forEach(col => { d3.range(0, 6).forEach(r => { dots.append("circle") .attr("cx", dotStartX + col * 8) .attr("cy", dotStartY + r * 8) .attr("r", 1.1) .attr("fill", roseSoft); }); });
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_10", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.jsfunction makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; // 默认为百分比 if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 3. 数据处理 ----------
const rawData = [...chartData].map((d, i) => ({ ...d, __originalIndex: i })); const dimensionValues = rawData.map(d => d[dimensionField]);
const parseMonth = (value) => { const text = String(value || "").trim().toLowerCase(); const monthNames = { 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 }; return monthNames[text] || null; };
const parseSeason = (value) => { const text = String(value || "").trim().toLowerCase(); const seasons = { spring: 1, summer: 2, fall: 3, autumn: 3, winter: 4 }; return seasons[text] || null; };
const temporalKey = (value) => { const text = String(value || "").trim(); const timeMatch = text.match(/^(\d{1,2}):(\d{2})(?:\s*(AM|PM))?$/i); if (timeMatch) { let hour = +timeMatch[1]; const minute = +timeMatch[2]; const period = timeMatch[3] ? timeMatch[3].toUpperCase() : null; if (period === "PM" && hour < 12) hour += 12; if (period === "AM" && hour === 12) hour = 0; return hour * 60 + minute; }
const yearMatch = text.match(/^(?:FY|CY)?\s*(\d{4})$/i); if (yearMatch) return +yearMatch[1] * 10000;
const semesterMatch = text.match(/^(?:semester|sem)\s*(\d+)\s*(?:[- ]?(\d{4}))?$/i); if (semesterMatch) { const year = semesterMatch[2] ? +semesterMatch[2] : 0; return year * 10 + +semesterMatch[1]; }
const quarterMatch = text.match(/^(?:Q([1-4])\s*(\d{4})|(\d{4})\s*Q([1-4]))$/i); if (quarterMatch) { const q = quarterMatch[1] || quarterMatch[4]; const year = quarterMatch[2] || quarterMatch[3]; return +year * 10 + +q; }
const month = parseMonth(text); if (month) return month;
const season = parseSeason(text); if (season) return season;
const parsedDate = Date.parse(text); if (!Number.isNaN(parsedDate)) return parsedDate;
return null; };
const temporalName = /time|date|month|year|season|semester|timestamp|hour|day|week|quarter/i.test(dimensionField); const temporalValues = dimensionValues .map(temporalKey) .filter(v => typeof v === "number" && Number.isFinite(v)); const isTemporalDimension = temporalName || temporalValues.length === dimensionValues.length;
const sortedData = [...rawData].sort((a, b) => { if (isTemporalDimension) { const ak = temporalKey(a[dimensionField]); const bk = temporalKey(b[dimensionField]); if (ak !== null && bk !== null && ak !== bk) return ak - bk; return a.__originalIndex - b.__originalIndex; } const valueDelta = +b[valueField] - +a[valueField]; if (valueDelta !== 0) return valueDelta; return a.__originalIndex - b.__originalIndex; }); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数
// 根据条形高度计算icon尺寸 const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; const prefix = currentLine === "" ? "" : `${currentLine} `; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = prefix + chars + char; const testLineWithHyphen = prefix + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: prefix + chars }; };
const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; };
// ---------- 4. 尺寸和布局计算 ----------
const width = Math.max(variables.width || 800, 1100); const baseHeight = Math.max(variables.height || 600, 600); const adjustedHeight = Math.max(560, Math.min(baseHeight, 132 + sortedData.length * 36 + 72)); const primaryColor = colorResolver.other("primary", { fallback: "#2F7FEA" }).value; const secondaryColor = colorResolver.other("secondary", { fallback: "#BFD9FF" }).value; const textColor = colorResolver.text({ fallback: "#10234B" }).value; const darkText = "#0D2148"; const mutedText = "#5D6E8D"; const rightSlotEnabled = width >= 560 && sortedData.length <= 16; const outerPad = Math.max(10, width * 0.018); const chartTop = 10; const chartBottom = 70; const rowsAreaHeight = adjustedHeight - chartTop - chartBottom; const rowStep = rowsAreaHeight / sortedData.length; const rowCardHeight = Math.min(42, Math.max(25, rowStep * 0.86)); const barHeight = Math.min(23, Math.max(12, rowCardHeight * 0.44)); const iconBox = Math.min(30, Math.max(18, rowCardHeight * 0.78)); const iconSize = calcIconSize(iconBox, { maxSize: iconBox * 0.72, minRatio: 0.72, minPx: 12 }); const labelMaxWidth = rightSlotEnabled ? Math.min(width * 0.12, 118) : width * 0.24; const dimLabelLayout = buildDimLabelLayout({ containerSelector: containerSelector, labels: sortedDimensions, fontConfig: typography.label, maxWidth: labelMaxWidth, maxHeight: rowCardHeight * 0.92, lineSpacing: 1.12, targetFontSize: Math.min(15.5, rowCardHeight * 0.38) }); const dimLabelConfig = dimLabelLayout.dimLabelConfig; const labelColumnWidth = Math.max(labelMaxWidth, dimLabelLayout.maxLabelWidth + 8); const rightSlotWidth = rightSlotEnabled ? Math.max(230, Math.min(width * 0.28, 330)) : 0; const rankX = outerPad + 18; const iconX = rankX + 34; const labelX = iconX + iconBox + 16; const plotX = rightSlotEnabled ? Math.max(labelX + Math.min(labelColumnWidth, width * 0.11) + 18, width * 0.235) : labelX + labelColumnWidth + 12; const rightSlotX = rightSlotEnabled ? width - outerPad - rightSlotWidth : width - outerPad; const plotRight = rightSlotEnabled ? rightSlotX - 18 : width - outerPad; const plotWidth = Math.max(120, plotRight - plotX); const axisY = chartTop + rowsAreaHeight + 18; const rightSlotY = chartTop + 4; const rightSlotH = Math.max(230, rowsAreaHeight - 4); const primaryVisualY = rightSlotY + Math.max(42, rightSlotH * 0.10); const primaryVisualH = Math.max(100, Math.min(rightSlotH * 0.48, rightSlotH - 178)); const primaryVisualX = rightSlotX + Math.max(18, rightSlotWidth * 0.12); const primaryVisualW = Math.max(52, rightSlotWidth - Math.max(36, rightSlotWidth * 0.24)); const maxValue = d3.max(sortedData, d => +d[valueField]) || 1; const axisMax = d3.scaleLinear() .domain([0, maxValue]) .nice(5) .domain()[1]; const xScale = d3.scaleLinear() .domain([0, axisMax]) .range([0, plotWidth]);
const formatValue = (value) => { const formatted = chartUtils.format.autoText(+value); return valueUnit ? `${formatted}${valueUnit}` : formatted; };
const formatAxisValue = (value) => { if (Math.abs(value) >= 1000) return `${chartUtils.format.autoText(value)}`; return chartUtils.format.autoText(value); };
const humanizeFieldLabel = (fieldName) => { const raw = String(fieldName || "").trim(); if (!raw) return ""; const spaced = raw .replace(/[_-]+/g, " ") .replace(/([a-z0-9])([A-Z])/g, "$1 $2") .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") .replace(/\s+/g, " ") .trim(); return spaced.replace(/\b\w/g, c => c.toUpperCase()); };
const valueDisplayLabel = humanizeFieldLabel(valueField);
const roundedRightBarPath = (x, y, w, h, r) => { const rr = Math.min(r, h / 2, Math.max(0, w)); return [ `M ${x},${y}`, `L ${x + w - rr},${y}`, `Q ${x + w},${y} ${x + w},${y + rr}`, `L ${x + w},${y + h - rr}`, `Q ${x + w},${y + h} ${x + w - rr},${y + h}`, `L ${x},${y + h}`, "Z" ].join(" "); };
// ---------- 5. 创建SVG容器 ----------
const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", adjustedHeight) .attr("viewBox", `0 0 ${width} ${adjustedHeight}`) .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink");
const defs = svg.append("defs"); const gradient = defs.append("linearGradient") .attr("id", "hbar10-bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%");
gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.18 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.12 }));
const shadow = defs.append("filter") .attr("id", "hbar10-soft-shadow") .attr("x", "-20%") .attr("y", "-40%") .attr("width", "150%") .attr("height", "190%"); shadow.append("feDropShadow") .attr("dx", 1.2) .attr("dy", 2) .attr("stdDeviation", 2.2) .attr("flood-color", "#0A3D88") .attr("flood-opacity", 0.18);
const primaryClip = defs.append("clipPath") .attr("id", "hbar10-primary-visual-clip"); primaryClip.append("rect") .attr("x", primaryVisualX) .attr("y", primaryVisualY) .attr("width", primaryVisualW) .attr("height", primaryVisualH) .attr("rx", 16) .attr("ry", 16);
const chart = svg.append("g") .attr("class", "horizontal-bar-chart-10") .attr("data-temporal-order", isTemporalDimension ? "chronological" : "value-desc") .attr("data-reference-endpoint-shape", "square-left-rounded-right") .attr("data-no-copied-reference-art", "true");
sortedData.forEach((dataPoint, index) => { const dimension = dataPoint[dimensionField]; const centerY = chartTop + index * rowStep + rowStep / 2; const rowY = centerY - rowCardHeight / 2; const barY = centerY - barHeight / 2; const barWidth = Math.max(2, xScale(+dataPoint[valueField])); const barRadius = Math.min(10, barHeight / 2); const formattedValue = formatValue(+dataPoint[valueField]); const valueTextWidth = chartUtils.text.measure(svg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: `${Math.min(17, Math.max(11, barHeight * 0.72))}px`, fontWeight: 700 }).width; const labelInside = barWidth > valueTextWidth + 22; const valueX = labelInside ? plotX + barWidth - 8 : plotX + barWidth + 8;
const rowGroup = chart.append("g") .attr("class", "hbar10-row") .attr("data-row-index", index) .attr("data-category", dimension) .attr("data-value", +dataPoint[valueField]);
rowGroup.append("line") .attr("x1", outerPad) .attr("x2", plotRight + 10) .attr("y1", rowY + rowCardHeight) .attr("y2", rowY + rowCardHeight) .attr("stroke", "#CFE3F5") .attr("stroke-width", 1) .attr("stroke-opacity", 0.72);
rowGroup.append("circle") .attr("cx", rankX) .attr("cy", centerY) .attr("r", Math.min(11, rowCardHeight * 0.31)) .attr("fill", primaryColor) .attr("stroke", "#FFFFFF") .attr("stroke-width", 1.4);
rowGroup.append("text") .attr("x", rankX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(11, rowCardHeight * 0.28)}px`) .style("font-weight", 700) .style("fill", "#FFFFFF") .text(index + 1);
rowGroup.append("rect") .attr("x", iconX) .attr("y", centerY - iconBox / 2) .attr("width", iconBox) .attr("height", iconBox) .attr("rx", 8) .attr("fill", "#FFFFFF") .attr("stroke", "#DCEAF7") .attr("filter", "url(#hbar10-soft-shadow)") .attr("data-asset-slot", "row-icon") .attr("data-anchor", "row-centerline") .attr("data-bbox", `${iconX},${centerY - iconBox / 2},${iconBox},${iconBox}`) .attr("data-collision", "avoid-row-label-and-rank") .attr("data-no-copied-reference-art", "true") .attr("data-no-embedded-raster", "input-provided-only");
if (images.field && images.field[dimension]) { rowGroup.append("image") .attr("x", iconX + (iconBox - iconSize.width) / 2) .attr("y", centerY - iconSize.height / 2) .attr("width", iconSize.width) .attr("height", iconSize.height) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xlink:href", images.field[dimension]); } else { rowGroup.append("circle") .attr("cx", iconX + iconBox / 2) .attr("cy", centerY) .attr("r", iconBox * 0.18) .attr("fill", secondaryColor) .attr("opacity", 0.7); }
const labelConfig = dimLabelConfig[dimension]; const labelGroup = rowGroup.append("text") .attr("x", labelX) .attr("text-anchor", "start") .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", 700) .style("fill", darkText);
if (labelConfig.needsWrapping) { const lineHeight = labelConfig.lineHeight; const startY = centerY - ((labelConfig.lines.length - 1) * lineHeight) / 2; labelGroup.attr("y", 0); labelConfig.lines.forEach((line, lineIndex) => { labelGroup.append("tspan") .attr("x", labelX) .attr("y", startY + lineIndex * lineHeight) .attr("dy", "0.35em") .text(line); }); } else { labelGroup .attr("y", centerY) .attr("dy", "0.35em") .text(labelConfig.lines[0]); }
rowGroup.append("path") .attr("class", "hbar10-bar") .attr("data-endpoint-shape", "square-left-rounded-right") .attr("data-left-baseline-edge", "square-flat") .attr("data-right-value-edge", "rounded") .attr("data-stacked-joins", "not-applicable") .attr("d", roundedRightBarPath(plotX, barY, barWidth, barHeight, barRadius)) .attr("fill", "url(#hbar10-bar-gradient)") .attr("filter", "url(#hbar10-soft-shadow)");
rowGroup.append("text") .attr("x", Math.min(valueX, plotRight - 4)) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", labelInside ? "end" : "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(17, Math.max(11, barHeight * 0.72))}px`) .style("font-weight", 700) .style("fill", labelInside ? "#FFFFFF" : colorResolver.variant(primaryColor, { mode: "darker", amount: 0.35 })) .text(formattedValue); });
const axis = chart.append("g") .attr("class", "hbar10-axis") .attr("transform", `translate(${plotX}, ${axisY})`);
axis.append("line") .attr("x1", 0) .attr("x2", plotWidth) .attr("y1", 0) .attr("y2", 0) .attr("stroke", "#8AA5C8") .attr("stroke-width", 1.2);
xScale.ticks(5).forEach(tick => { const x = xScale(tick); axis.append("line") .attr("x1", x) .attr("x2", x) .attr("y1", -4) .attr("y2", 4) .attr("stroke", "#8AA5C8") .attr("stroke-width", 1); axis.append("text") .attr("x", x) .attr("y", 20) .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", "10px") .style("font-weight", 500) .style("fill", mutedText) .text(formatAxisValue(tick)); });
axis.append("text") .attr("x", plotWidth / 2) .attr("y", 42) .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", "11px") .style("font-weight", 600) .style("fill", mutedText) .text(valueUnit === "$" ? `${valueDisplayLabel} (K$)` : `${valueDisplayLabel}${valueUnit ? ` (${valueUnit})` : ""}`);
if (rightSlotEnabled) { const highlightDatum = sortedData.reduce((best, datum) => { if (!best) return datum; return +datum[valueField] > +best[valueField] ? datum : best; }, null) || sortedData[0]; const slotY = rightSlotY; const slotH = rightSlotH; const visualY = primaryVisualY; const visualH = primaryVisualH; const visualX = primaryVisualX; const visualW = primaryVisualW; const primaryImage = images.other && images.other.primary;
const slotGroup = chart.append("g") .attr("class", "hbar10-primary-visual-slot") .attr("data-asset-slot", "primary-visual") .attr("data-anchor", "chart-body-right-column") .attr("data-bbox", `${rightSlotX},${slotY},${rightSlotWidth},${slotH}`) .attr("data-mask", "hbar10-primary-visual-clip") .attr("data-collision", "avoid-title-subtitle-bars-labels-values-axis") .attr("data-no-embedded-raster", "input-provided-only") .attr("data-no-copied-reference-art", "true");
slotGroup.append("rect") .attr("x", rightSlotX) .attr("y", slotY) .attr("width", rightSlotWidth) .attr("height", slotH) .attr("rx", 18) .attr("fill", "rgba(255,255,255,0.78)") .attr("stroke", "#D8B05B") .attr("stroke-opacity", 0.7);
const badge = slotGroup.append("g") .attr("data-asset-slot", "highlight-badge") .attr("data-anchor", "right-card-top-center") .attr("data-bbox", `${rightSlotX + rightSlotWidth / 2 - 14},${slotY - 2},28,28`) .attr("data-collision", "inside-primary-visual-slot") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true");
badge.append("circle") .attr("cx", rightSlotX + rightSlotWidth / 2) .attr("cy", slotY + 14) .attr("r", 14) .attr("fill", "#FFFFFF") .attr("stroke", primaryColor) .attr("stroke-width", 2); badge.append("text") .attr("x", rightSlotX + rightSlotWidth / 2) .attr("y", slotY + 14) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", "12px") .style("font-weight", 800) .style("fill", primaryColor) .text("1");
slotGroup.append("rect") .attr("x", visualX) .attr("y", visualY) .attr("width", visualW) .attr("height", visualH) .attr("rx", 16) .attr("fill", "#EAF4FC") .attr("stroke", "#D3E7F5");
if (primaryImage) { slotGroup.append("image") .attr("x", visualX) .attr("y", visualY) .attr("width", visualW) .attr("height", visualH) .attr("preserveAspectRatio", "xMidYMid meet") .attr("clip-path", "url(#hbar10-primary-visual-clip)") .attr("xlink:href", primaryImage); } else { slotGroup.append("text") .attr("x", visualX + visualW / 2) .attr("y", visualY + visualH / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", "10px") .style("font-weight", 700) .style("fill", mutedText) .text("IMAGE SLOT"); }
const topLabel = String(highlightDatum[dimensionField] || ""); const topLines = topLabel.split(/\s+/).reduce((lines, word) => { const last = lines[lines.length - 1] || ""; const next = last ? `${last} ${word}` : word; if (next.length > 12 && last) lines.push(word); else lines[lines.length - 1] = next; return lines; }, [""]).slice(0, 3);
const titleY = visualY + visualH + 30; const topText = slotGroup.append("text") .attr("x", rightSlotX + rightSlotWidth / 2) .attr("y", titleY) .attr("text-anchor", "middle") .style("font-family", typography.title.font_family) .style("font-size", "17px") .style("font-weight", 900) .style("fill", darkText);
topLines.forEach((line, i) => { topText.append("tspan") .attr("x", rightSlotX + rightSlotWidth / 2) .attr("dy", i === 0 ? 0 : 19) .text(line.toUpperCase()); });
const emphasisY = titleY + Math.max(46, topLines.length * 19 + 18); const emphasisText = slotGroup.append("text") .attr("x", rightSlotX + rightSlotWidth / 2) .attr("y", emphasisY) .attr("text-anchor", "middle") .attr("data-card-content", "data-bound-highlight-summary") .attr("data-no-copied-reference-art", "true") .style("font-family", typography.title.font_family) .style("font-size", "15px") .style("font-weight", 900) .style("fill", "#C58A23");
emphasisText.append("tspan") .attr("x", rightSlotX + rightSlotWidth / 2) .attr("dy", 0) .text("HIGHEST"); emphasisText.append("tspan") .attr("x", rightSlotX + rightSlotWidth / 2) .attr("dy", 18) .text(valueDisplayLabel.toUpperCase());
const dividerY = emphasisY + 42; slotGroup.append("line") .attr("x1", rightSlotX + 26) .attr("x2", rightSlotX + rightSlotWidth / 2 - 14) .attr("y1", dividerY) .attr("y2", dividerY) .attr("stroke", "#D8B05B") .attr("stroke-width", 1.2);
slotGroup.append("rect") .attr("x", rightSlotX + rightSlotWidth / 2 - 4) .attr("y", dividerY - 4) .attr("width", 8) .attr("height", 8) .attr("transform", `rotate(45 ${rightSlotX + rightSlotWidth / 2} ${dividerY})`) .attr("fill", "#D8B05B") .attr("data-asset-slot", "neutral-divider-ornament") .attr("data-anchor", "right-card-divider-center") .attr("data-bbox", `${rightSlotX + rightSlotWidth / 2 - 4},${dividerY - 4},8,8`) .attr("data-collision", "inside-right-card-between-emphasis-and-value") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true");
slotGroup.append("line") .attr("x1", rightSlotX + rightSlotWidth / 2 + 14) .attr("x2", rightSlotX + rightSlotWidth - 26) .attr("y1", dividerY) .attr("y2", dividerY) .attr("stroke", "#D8B05B") .attr("stroke-width", 1.2);
slotGroup.append("text") .attr("x", rightSlotX + rightSlotWidth / 2) .attr("y", dividerY + 33) .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", "20px") .style("font-weight", 900) .style("fill", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.2 })) .text(formatValue(+highlightDatum[valueField])); }
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_11", "is_composite": true, "required_fields": ["x", "y", "y2", "group"], "required_fields_type": [["categorical", "temporal"], ["numerical"], ["numerical"], ["categorical"]], "required_fields_range": [[2, 16], [0, 10000], [0, 10000], [2, 6]], "required_fields_icons": [], "hierarchy": ["group"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "styled", "icon_mark": "none", "icon_label": "none", "has_x_axis": "yes", "has_y_axis": "yes"}REQUIREMENTS_END*/
// Horizontal bar chart with a secondary value column and group text encoding.function makeChart(containerSelector, data) { const jsonData = data; const chartData = jsonData.data.data || []; const variables = jsonData.variables || {}; const typography = jsonData.typography || { label: { font_family: "Arial", font_size: "12px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } }; const sourceColors = jsonData.colors || { text_color: "#333333", other: { primary: "#1d6b64" }, field: {} }; 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 } });
variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; variables.has_gradient = variables.has_gradient || false;
d3.select(containerSelector).html("");
const width = Math.max(720, Number(variables.width) || 800); const baseHeight = Number(variables.height) || 600; const textColor = sourceColors.text_color || "#333333"; const primaryColor = sourceColors.other && sourceColors.other.primary ? sourceColors.other.primary : "#1d6b64"; const labelFont = typography.label || {}; const valueFont = typography.annotation || {}; const labelFontSize = parseFloat(labelFont.font_size) || 12; const valueFontSize = parseFloat(valueFont.font_size) || 12;
const dimensionField = chartUtils.schema.channel(jsonData, "x", { fallbackIndex: 0 }).raw?.name || chartUtils.schema.column(dataColumns, 0).raw?.name || "dimension"; const valueField = chartUtils.schema.channel(jsonData, "y", { fallbackIndex: 1 }).raw?.name || chartUtils.schema.column(dataColumns, 1).raw?.name || "value"; const valueField2 = chartUtils.schema.channel(jsonData, "y2", { fallbackIndex: 2 }).raw?.name || chartUtils.schema.column(dataColumns, 2).raw?.name || "total"; const groupField = chartUtils.schema.channel(jsonData, "group", { fallbackIndex: 2 }).raw?.name || chartUtils.schema.column(dataColumns, 3).raw?.name || "group"; const dimensionColumn = chartUtils.schema.channel(jsonData, "x", { fallbackIndex: 0 }).raw || {}; const valueColumn = chartUtils.schema.channel(jsonData, "y", { fallbackIndex: 1 }).raw || {}; const valueColumn2 = chartUtils.schema.channel(jsonData, "y2", { fallbackIndex: 2 }).raw || {};
const valueUnit = valueColumn.unit && valueColumn.unit !== "none" ? valueColumn.unit : ""; const valueUnit2 = valueColumn2.unit && valueColumn2.unit !== "none" ? valueColumn2.unit : ""; function humanizeFieldName(name) { return String(name ?? "") .replace(/[_-]+/g, " ") .replace(/([a-z0-9])([A-Z])/g, "$1 $2") .replace(/\s+/g, " ") .trim() .replace(/\b\w/g, letter => letter.toUpperCase()); }
function displayColumnName(column, fallbackName) { const raw = column.display_name || column.label || fallbackName; const readable = humanizeFieldName(raw); const unit = column.unit && column.unit !== "none" ? column.unit : ""; return unit && !readable.includes(unit) ? `${readable} (${unit})` : readable; }
const dimensionDisplayName = displayColumnName(dimensionColumn, dimensionField); const valueFieldName = displayColumnName(valueColumn, valueField); const valueField2Name = displayColumnName(valueColumn2, valueField2);
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 formatLocalValue(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 withUnit(value, unit) { const formatted = formatLocalValue(value); return unit ? `${formatted} ${unit}` : formatted; }
const temporalSortValues = chartData.map(d => parseTemporalSortValue(d[dimensionField])); const hasTemporalLikeX = ( dimensionColumn.data_type === "temporal" || temporalSortValues.every(Number.isFinite) );
const sortedData = [...chartData].sort((a, b) => { const aTemporal = parseTemporalSortValue(a[dimensionField]); const bTemporal = parseTemporalSortValue(b[dimensionField]); if (hasTemporalLikeX && Number.isFinite(aTemporal) && Number.isFinite(bTemporal)) { return aTemporal - bTemporal; } return Number(b[valueField]) - Number(a[valueField]); });
const groups = Array.from(new Set(sortedData.map(d => String(d[groupField] ?? "")))); const fallbackPalette = [ primaryColor, chartUtils.color.variant(primaryColor, { mode: "brighter", amount: 0.8 }), chartUtils.color.variant(primaryColor, { mode: "darker", amount: 0.8 }), "#5b8def", "#d47b51", "#6c9f6b" ]; const groupColor = d3.scaleOrdinal() .domain(groups) .range(groups.map((group, index) => { return (sourceColors.field && sourceColors.field[group]) || fallbackPalette[index % fallbackPalette.length]; }));
const rowCount = Math.max(sortedData.length, 1); const compact = width < 520 || rowCount > 10; const rowHeight = compact ? 48 : 64; const rowGap = compact ? 5 : 8; const outerPad = Math.max(12, Math.min(22, width * 0.03)); const headerHeight = compact ? 48 : 58; const chartTop = outerPad + 14; const bodyTop = chartTop + headerHeight + 10; const bodyHeight = rowCount * rowHeight + Math.max(0, rowCount - 1) * rowGap; const height = Math.max(baseHeight, bodyTop + bodyHeight + outerPad + 16);
const svg = d3.select(containerSelector) .append("svg") .attr("width", width) .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");
const defs = svg.append("defs"); const shadowFilter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("x", "-20%") .attr("y", "-20%") .attr("width", "140%") .attr("height", "150%"); shadowFilter.append("feDropShadow") .attr("dx", 0) .attr("dy", 2) .attr("stdDeviation", 3) .attr("flood-color", "#0b3b3f") .attr("flood-opacity", 0.16);
const gradient = defs.append("linearGradient") .attr("id", "horizontal-bar-gradient-11") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", chartUtils.color.variant(primaryColor, { mode: "brighter", amount: 0.62 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", chartUtils.color.variant(primaryColor, { mode: "darker", amount: 0.16 }));
function measureLabelText(text, fontFamily, fontSize, fontWeight) { const node = svg.append("text") .style("visibility", "hidden") .style("font-family", fontFamily) .style("font-size", fontSize) .style("font-weight", fontWeight) .text(String(text ?? "")); const bbox = chartUtils.text.nodeSize(node.node()); node.remove(); return bbox.width; }
function splitLabelLines(text, maxWidth, fontFamily, fontSize, fontWeight, maxLines = 2) { const rawText = String(text ?? "").trim(); if (!rawText) return [""]; if (measureLabelText(rawText, fontFamily, fontSize, fontWeight) <= maxWidth) { return [rawText]; } const words = rawText .replace(/[()[\]{}]/g, " ") .replace(/[,:;/\\|_-]+/g, " ") .split(/\s+/) .filter(Boolean); if (words.length <= 1) return [rawText];
const lines = []; let current = ""; for (const word of words) { const candidate = current ? `${current} ${word}` : word; if (measureLabelText(candidate, fontFamily, fontSize, fontWeight) <= maxWidth || current === "") { current = candidate; continue; } lines.push(current); current = word; if (lines.length === maxLines - 1) break; } if (current && lines.length < maxLines) lines.push(current); return lines.slice(0, maxLines); }
const panelFill = "#f7fbf8"; const navy = "#092244"; const teal = primaryColor; const tealDark = chartUtils.color.variant(primaryColor, { mode: "darker", amount: 0.65 }); const tealPale = chartUtils.color.variant(primaryColor, { mode: "brighter", amount: 1.55 }); const bodyX = outerPad; const bodyWidth = width - outerPad * 2; const labelColW = Math.max(132, Math.min(width * 0.34, bodyWidth * 0.28)); const secondaryColW = Math.max(86, Math.min(width * 0.23, bodyWidth * 0.2)); const iconSlot = compact ? 28 : 36; const leftTextX = bodyX + iconSlot + 18; const rightColX = bodyX + bodyWidth - secondaryColW; const barX = bodyX + labelColW + 16; const barW = Math.max(90, rightColX - barX - 16); const xMax = d3.max(sortedData, d => Number(d[valueField])) || 1; const xScale = d3.scaleLinear() .domain([0, xMax * 1.05]) .range([0, barW]);
svg.append("rect") .attr("class", "chart-background-panel") .attr("x", outerPad / 2) .attr("y", outerPad / 2) .attr("width", width - outerPad) .attr("height", height - outerPad) .attr("rx", Math.max(14, width * 0.025)) .attr("fill", panelFill) .attr("stroke", chartUtils.color.variant(primaryColor, { mode: "brighter", amount: 1.65 })) .attr("stroke-width", 1);
const header = svg.append("g") .attr("class", "chart-header-band"); header.append("rect") .attr("x", bodyX) .attr("y", chartTop) .attr("width", bodyWidth) .attr("height", headerHeight) .attr("rx", 10) .attr("fill", tealDark) .attr("filter", "url(#shadow)"); header.append("rect") .attr("x", bodyX + labelColW) .attr("y", chartTop) .attr("width", barW + 32) .attr("height", headerHeight) .attr("fill", teal) .attr("opacity", 0.85); header.append("line") .attr("x1", bodyX + labelColW) .attr("x2", bodyX + labelColW) .attr("y1", chartTop) .attr("y2", chartTop + headerHeight) .attr("stroke", "#ffffff") .attr("stroke-opacity", 0.75); header.append("line") .attr("x1", rightColX) .attr("x2", rightColX) .attr("y1", chartTop) .attr("y2", chartTop + headerHeight) .attr("stroke", "#ffffff") .attr("stroke-opacity", 0.75);
function addHeaderText(text, x, anchor, maxWidth) { const words = splitLabelLines(text, maxWidth, "Arial", `${compact ? 10 : 12}px`, 700, 2); const group = header.append("text") .attr("x", x) .attr("y", chartTop + headerHeight / 2 - (words.length - 1) * 7) .attr("text-anchor", anchor) .style("dominant-baseline", "middle") .style("font-family", "Arial") .style("font-size", `${compact ? 10 : 12}px`) .style("font-weight", 700) .style("letter-spacing", "0") .style("fill", "#ffffff"); words.forEach((line, i) => { group.append("tspan") .attr("x", x) .attr("dy", i === 0 ? 0 : 14) .text(line.toUpperCase()); }); } addHeaderText(dimensionDisplayName, bodyX + labelColW / 2, "middle", labelColW - 18); addHeaderText(valueFieldName, barX + barW / 2, "middle", barW - 18); addHeaderText(valueField2Name, rightColX + secondaryColW / 2, "middle", secondaryColW - 12);
const rowLabelFontSize = Math.max(11, Math.min(15, labelFontSize * (compact ? 0.78 : 0.9))); const groupFontSize = Math.max(8, Math.min(11, rowLabelFontSize * 0.78)); const primaryValueFontSize = Math.max(10, Math.min(14, valueFontSize * 0.98)); const secondaryFontSize = Math.max(15, Math.min(23, valueFontSize * (compact ? 1.15 : 1.45))); const barHeight = compact ? 20 : 26; const rightTopicSlotSize = Math.max(20, Math.min(compact ? 27 : 34, secondaryColW * 0.23, rowHeight - 18)); const rightTopicSlotX = rightColX + secondaryColW - rightTopicSlotSize - 13; const secondaryTextX = rightColX + secondaryColW * 0.43; const showPerRowTicks = rowCount <= 7 && !compact;
sortedData.forEach((d, index) => { const y = bodyTop + index * (rowHeight + rowGap); const rowCenterY = y + rowHeight / 2; const group = String(d[groupField] ?? ""); const barColor = groupColor(group); const barWidth = Math.max(1, xScale(Number(d[valueField]) || 0)); const valueText = withUnit(d[valueField], valueUnit); const secondaryText = withUnit(d[valueField2], valueUnit2);
svg.append("rect") .attr("class", "row-card") .attr("x", bodyX) .attr("y", y) .attr("width", bodyWidth) .attr("height", rowHeight) .attr("rx", compact ? 8 : 12) .attr("fill", "#ffffff") .attr("stroke", chartUtils.color.variant(primaryColor, { mode: "brighter", amount: 1.45 })) .attr("stroke-width", 0.6) .attr("filter", "url(#shadow)");
const icon = svg.append("g") .attr("class", "asset-slot row-icon-slot") .attr("data-asset-slot", "row-icon") .attr("data-asset-anchor", "row-center") .attr("data-asset-row-index", index) .attr("data-asset-bbox", `${bodyX + 12},${rowCenterY - iconSlot / 2},${iconSlot},${iconSlot}`) .attr("data-asset-collision", "avoid-row-label-and-card-edge") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true"); icon.append("circle") .attr("cx", bodyX + 12 + iconSlot / 2) .attr("cy", rowCenterY) .attr("r", iconSlot / 2) .attr("fill", chartUtils.color.variant(barColor, { mode: "brighter", amount: 1.2 })) .attr("stroke", barColor) .attr("stroke-width", 1.2) .attr("opacity", 0.95); icon.append("circle") .attr("cx", bodyX + 12 + iconSlot / 2) .attr("cy", rowCenterY) .attr("r", Math.max(3, iconSlot * 0.12)) .attr("fill", barColor) .attr("opacity", 0.65);
const labelLines = splitLabelLines( d[dimensionField], Math.max(48, labelColW - iconSlot - 32), "Arial", `${rowLabelFontSize}px`, 700, 2 ); const label = svg.append("text") .attr("class", "label") .attr("x", leftTextX) .attr("y", rowCenterY - (labelLines.length > 1 ? 8 : 3)) .attr("text-anchor", "start") .style("font-family", labelFont.font_family || "Arial") .style("font-size", `${rowLabelFontSize}px`) .style("font-weight", 700) .style("fill", navy); labelLines.forEach((line, lineIndex) => { label.append("tspan") .attr("x", leftTextX) .attr("dy", lineIndex === 0 ? 0 : rowLabelFontSize + 1) .text(line); });
svg.append("text") .attr("class", "group-label") .attr("x", leftTextX) .attr("y", rowCenterY + rowLabelFontSize + 6) .attr("text-anchor", "start") .style("font-family", labelFont.font_family || "Arial") .style("font-size", `${groupFontSize}px`) .style("fill", "#566373") .text(group);
svg.append("line") .attr("class", "axis-baseline") .attr("x1", barX) .attr("x2", barX + barW) .attr("y1", rowCenterY + barHeight / 2 + 8) .attr("y2", rowCenterY + barHeight / 2 + 8) .attr("stroke", "#6b7a8e") .attr("stroke-width", 0.6) .attr("opacity", showPerRowTicks ? 0.22 : 0.1); if (showPerRowTicks) { [0, 0.5, 1].forEach(tick => { const tickX = barX + barW * tick; svg.append("text") .attr("class", "axis-tick") .attr("x", tickX) .attr("y", rowCenterY + barHeight / 2 + 22) .attr("text-anchor", "middle") .style("font-family", "Arial") .style("font-size", "8px") .style("fill", "#566373") .style("opacity", 0.74) .text(tick === 0 ? "0" : tick === 0.5 ? "50%" : "100%"); }); }
const barGradientId = `horizontal-bar-gradient-11-${index}`; const localGradient = defs.append("linearGradient") .attr("id", barGradientId) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); localGradient.append("stop") .attr("offset", "0%") .attr("stop-color", chartUtils.color.variant(barColor, { mode: "brighter", amount: 0.55 })); localGradient.append("stop") .attr("offset", "100%") .attr("stop-color", chartUtils.color.variant(barColor, { mode: "darker", amount: 0.1 }));
const radius = Math.min(6, barHeight * 0.22); svg.append("rect") .attr("class", "bar mark") .attr("data-row-index", index) .attr("data-category", String(d[dimensionField] ?? "")) .attr("data-value", Number(d[valueField]) || 0) .attr("x", barX) .attr("y", rowCenterY - barHeight / 2) .attr("width", barWidth) .attr("height", barHeight) .attr("rx", radius) .attr("ry", radius) .attr("fill", `url(#${barGradientId})`) .attr("stroke", chartUtils.color.variant(barColor, { mode: "darker", amount: 0.25 })) .attr("stroke-width", 0.8) .style("opacity", 0.96);
const valueTextWidth = measureLabelText(valueText, "Arial", `${primaryValueFontSize}px`, 700); const fitsInside = barWidth > valueTextWidth + 12; svg.append("text") .attr("class", "value primary-value") .attr("x", fitsInside ? barX + barWidth - 7 : barX + barWidth + 6) .attr("y", rowCenterY + 1) .attr("text-anchor", fitsInside ? "end" : "start") .style("dominant-baseline", "middle") .style("font-family", valueFont.font_family || "Arial") .style("font-size", `${primaryValueFontSize}px`) .style("font-weight", 700) .style("fill", fitsInside ? "#ffffff" : navy) .text(valueText);
svg.append("line") .attr("class", "secondary-divider") .attr("x1", rightColX) .attr("x2", rightColX) .attr("y1", y + 8) .attr("y2", y + rowHeight - 8) .attr("stroke", chartUtils.color.variant(primaryColor, { mode: "brighter", amount: 1.25 })) .attr("stroke-width", 1);
const topicSlot = svg.append("g") .attr("class", "asset-slot right-column-topic-art-slot") .attr("data-asset-slot", "right-column-topic-art") .attr("data-asset-anchor", "right-secondary-cell-far-right") .attr("data-asset-row-index", index) .attr("data-asset-bbox", `${rightTopicSlotX},${rowCenterY - rightTopicSlotSize / 2},${rightTopicSlotSize},${rightTopicSlotSize}`) .attr("data-asset-collision", "avoid-secondary-value-divider-row-card-and-adjacent-rows") .attr("data-asset-source-policy", "image2_asset") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true"); topicSlot.append("rect") .attr("x", rightTopicSlotX) .attr("y", rowCenterY - rightTopicSlotSize / 2) .attr("width", rightTopicSlotSize) .attr("height", rightTopicSlotSize) .attr("rx", rightTopicSlotSize * 0.32) .attr("fill", tealPale) .attr("opacity", 0.28); topicSlot.append("line") .attr("x1", rightTopicSlotX + rightTopicSlotSize * 0.24) .attr("x2", rightTopicSlotX + rightTopicSlotSize * 0.76) .attr("y1", rowCenterY) .attr("y2", rowCenterY) .attr("stroke", tealDark) .attr("stroke-width", Math.max(1.2, rightTopicSlotSize * 0.08)) .attr("stroke-linecap", "round") .attr("opacity", 0.2);
svg.append("text") .attr("class", "value secondary-value") .attr("x", secondaryTextX) .attr("y", rowCenterY + 1) .attr("text-anchor", "middle") .style("dominant-baseline", "middle") .style("font-family", valueFont.font_family || "Arial") .style("font-size", `${secondaryFontSize}px`) .style("font-weight", 700) .style("fill", navy) .text(secondaryText); });
if (!showPerRowTicks) { const bottomAxisY = bodyTop + bodyHeight + 8; svg.append("line") .attr("class", "axis-baseline axis-baseline-shared") .attr("x1", barX) .attr("x2", barX + barW) .attr("y1", bottomAxisY) .attr("y2", bottomAxisY) .attr("stroke", "#6b7a8e") .attr("stroke-width", 0.7) .attr("opacity", 0.28); [0, 0.5, 1].forEach(tick => { const tickX = barX + barW * tick; svg.append("text") .attr("class", "axis-tick axis-tick-shared") .attr("x", tickX) .attr("y", bottomAxisY + 13) .attr("text-anchor", "middle") .style("font-family", "Arial") .style("font-size", "8px") .style("fill", "#566373") .style("opacity", 0.78) .text(tick === 0 ? "0" : tick === 0.5 ? "50%" : "100%"); }); }
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_12", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 600, "background": "styled", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.jsfunction makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data; // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 60, // 顶部留出标题空间 right: 60, // 右侧足够显示数值 bottom: 30, // 底部边距 left: 220 // 左侧空间用于参考图的图标列和标签列 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionChannel = chartUtils.schema.column(dataColumns, 0, { fallbackKey: "dimension" }); const valueChannel = chartUtils.schema.column(dataColumns, 1, { fallbackKey: "value" }); const dimensionField = dimensionChannel.key; const valueField = valueChannel.key; const dimensionUnit = dimensionChannel.unit; const valueUnit = valueChannel.unit; // ---------- 4. 数据处理 ---------- // 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 如果x维度数量超过15,每增加一个x,整个图像的高度增加3% const baseHeight = variables.height || 600; const adjustedHeight = dimensions.length > 15 ? baseHeight * (1 + (dimensions.length - 15) * 0.03) : baseHeight; // 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数
// 计算图标尺寸 const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
// 智能换行:优先按单词;利用率不足50%时尝试塞字母;长词断行加"-";断词后下一行单字母开头尽量回并 const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = formatDisplayLabel(labels[i]); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = formatDisplayLabel(label); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; };
// ---------- 5. 计算标签宽度 ----------
// 计算条形高度和图标尺寸 const barPadding = variables.has_spacing ? 0.3 : 0.2; const tempYScale = d3.scaleBand() .domain(sortedDimensions) .range([0, height - margin.top - margin.bottom]) .padding(barPadding);
const barHeight = tempYScale.bandwidth(); const iconSize = calcIconSize(barHeight, { maxSize: 48, minRatio: 0.8, minPx: 10 }); const flagWidth = iconSize.width; const flagHeight = iconSize.height; const flagPadding = 5;
// 使用智能换行计算维度标签布局 const formatDisplayLabel = (text) => String(text || "") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/\s+/g, " ") .trim();
const labelFontSize = Math.min(parseFloat(typography.label.font_size) || 12, 12.5); const labelMaxWidth = 120; const labelMaxHeight = barHeight; const labelLineSpacing = 1.2;
const labelLayoutResult = buildDimLabelLayout({ containerSelector: containerSelector, labels: sortedDimensions, fontConfig: { font_family: typography.label.font_family, font_weight: typography.label.font_weight }, maxWidth: labelMaxWidth, maxHeight: labelMaxHeight, lineSpacing: labelLineSpacing, targetFontSize: labelFontSize });
const dimLabelConfig = labelLayoutResult.dimLabelConfig; const maxLabelWidth = labelLayoutResult.maxLabelWidth;
// 计算最大数值标签宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`;
const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width; maxValueWidth = Math.max(maxValueWidth, textWidth); });
tempSvg.remove();
// 根据标签宽度调整左边距 const totalLabelWidth = flagWidth + flagPadding + maxLabelWidth; margin.left = Math.max(margin.left, totalLabelWidth + 20); margin.right = Math.max(margin.right, maxValueWidth + 20); // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } const primaryColor = colorResolver.other("primary", { fallback: "#F28A22" }).value; const barGradientId = `bar-gradient-${Math.random().toString(36).slice(2)}`; const rowShadowId = `row-shadow-${Math.random().toString(36).slice(2)}`;
const barGradient = defs.append("linearGradient") .attr("id", barGradientId) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%");
barGradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.08 }));
barGradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.42 }));
const rowShadow = defs.append("filter") .attr("id", rowShadowId) .attr("x", "-8%") .attr("y", "-20%") .attr("width", "116%") .attr("height", "140%");
rowShadow.append("feDropShadow") .attr("dx", 0) .attr("dy", 2) .attr("stdDeviation", 2.2) .attr("flood-color", "#153B4D") .attr("flood-opacity", 0.10); // ---------- 7. 创建比例尺 ----------
// Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
// X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添加5%边距 .range([0, innerWidth]); // ---------- 8. 添加标题和副标题 ---------- // 添加标题(如果有) if (variables.title && variables.title.text) { svg.append("text") .attr("x", margin.left) .attr("y", margin.top / 2) .attr("text-anchor", "start") .style("font-family", typography.title.font_family) .style("font-size", typography.title.font_size) .style("font-weight", typography.title.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(variables.title.text); } // 添加副标题(如果有) if (variables.subtitle && variables.subtitle.text) { svg.append("text") .attr("x", margin.left) .attr("y", margin.top / 2 + 20) .attr("text-anchor", "start") .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(variables.subtitle.text); } // ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制条形和标签 ---------- // 获取条形颜色的辅助函数 // 获取条形颜色的辅助函数 const getBarColor = () => { return colorResolver.other("primary", { fallback: "#882e2e" }).value; // 默认暗红色 };
// 获取描边颜色的辅助函数 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.available(0, { fallback: "#333333" }).value; }; const rowCardX = -margin.left + 10; const rowCardWidth = innerWidth + margin.left + margin.right - 20; const labelColumnX = -22; const iconX = -margin.left + 28; const cardGap = Math.max(6, yScale.step() * 0.08); const valueColor = "#0F6B58"; const labelColor = "#0B253D";
const rightRoundedBarPath = (x, y, w, h, r) => { const radius = Math.max(0, Math.min(r, h / 2, w)); if (w <= radius) { return `M${x},${y}H${x + w}V${y + h}H${x}Z`; } return [ `M${x},${y}`, `H${x + w - radius}`, `Q${x + w},${y} ${x + w},${y + radius}`, `V${y + h - radius}`, `Q${x + w},${y + h} ${x + w - radius},${y + h}`, `H${x}`, "Z" ].join(""); };
const slotW = Math.min(rowCardWidth * 0.54, Math.max(innerWidth * 0.86, 250)); const slotH = Math.min(innerHeight * 0.44, Math.max(160, innerHeight * 0.30)); const slotX = Math.max(labelColumnX + 54, innerWidth - slotW + margin.right * 0.52); const slotY = Math.max(innerHeight * 0.56, innerHeight - slotH + 4); const assetSlot = g.append("g") .attr("class", "reserved-asset-slot lower-right-illustration-slot") .attr("data-asset-slot", "lower_right_context_illustration") .attr("data-asset-source", "image2_asset") .attr("data-bbox", `${slotX},${slotY},${slotW},${slotH}`) .attr("data-anchor", "plot-lower-right") .attr("data-collision-rule", "large lower-right body slot behind row-cards-and-bars; downstream asset must avoid labels, baseline, bars, values, and canvas edge") .attr("data-mask", "plot-lower-right-large-reference-footprint") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-reference-footprint", "selected-reference-large-lower-right-context-illustration") .attr("opacity", 0.72);
assetSlot.append("rect") .attr("x", slotX) .attr("y", slotY) .attr("width", slotW) .attr("height", slotH) .attr("rx", 24) .attr("fill", "#CFEDE6") .attr("opacity", 0.30) .attr("stroke", "#62BDAF") .attr("stroke-width", 1.4) .attr("stroke-dasharray", "9 7");
assetSlot.append("path") .attr("d", `M${slotX + slotW * 0.06},${slotY + slotH * 0.78} C${slotX + slotW * 0.28},${slotY + slotH * 0.50} ${slotX + slotW * 0.54},${slotY + slotH * 0.92} ${slotX + slotW * 0.94},${slotY + slotH * 0.60}`) .attr("fill", "none") .attr("stroke", "#57B7A6") .attr("stroke-width", Math.max(16, Math.min(28, slotH * 0.14))) .attr("stroke-linecap", "round") .attr("opacity", 0.20);
assetSlot.append("circle") .attr("cx", slotX + slotW * 0.72) .attr("cy", slotY + slotH * 0.36) .attr("r", Math.min(slotW, slotH) * 0.26) .attr("fill", "#57B7A6") .attr("opacity", 0.16);
assetSlot.append("line") .attr("x1", slotX + slotW * 0.18) .attr("y1", slotY + slotH * 0.28) .attr("x2", slotX + slotW * 0.70) .attr("y2", slotY + slotH * 0.66) .attr("stroke", "#2E8F83") .attr("stroke-width", 2) .attr("stroke-dasharray", "7 8") .attr("opacity", 0.14);
// Reference row geometry: independent rounded cards span the label, baseline, bar, and value columns. sortedDimensions.forEach((dimension) => { g.append("rect") .attr("x", rowCardX) .attr("y", yScale(dimension) + cardGap / 2) .attr("width", rowCardWidth) .attr("height", yScale.bandwidth() - cardGap) .attr("rx", 8) .attr("class", "row-card") .attr("data-relationship", "grid-row-span-matched") .attr("fill", "#FFFFFF") .attr("opacity", 0.92) .style("filter", `url(#${rowShadowId})`); });
g.append("line") .attr("class", "bar-baseline-divider") .attr("data-relationship", "flush-baseline-for-bar-left-edges") .attr("x1", 0) .attr("x2", 0) .attr("y1", 0) .attr("y2", innerHeight) .attr("stroke", "#C6B9AA") .attr("stroke-width", 1.2); // 为每个维度绘制条形和标签 sortedDimensions.forEach(dimension => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]); const visualBarHeight = Math.max(10, Math.min(34, barHeight * 0.58)); const visualBarY = yScale(dimension) + (barHeight - visualBarHeight) / 2; const barRadius = Math.min(8, visualBarHeight / 2);
// 绘制条形:左端与基线齐平,右端圆角,匹配所选参考图的端点几何。 g.append("path") .attr("d", rightRoundedBarPath(0, visualBarY, barWidth, visualBarHeight, barRadius)) .attr("class", "bar-mark") .attr("data-bar-endpoint-geometry", "left-baseline-flat,right-value-rounded") .attr("fill", `url(#${barGradientId})`) .style("stroke", variables.has_stroke ? getStrokeColor() : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); }); // 添加带图标的维度标签 const centerY = yScale(dimension) + barHeight / 2; const labelX = labelColumnX;
// 添加图标(如果有) if (images.field && images.field[dimension]) { g.append("image") .attr("class", "field-icon input-asset-icon") .attr("data-asset-slot", `field_icon_${String(dimension).replace(/[^a-z0-9]+/gi, "_").toLowerCase()}`) .attr("data-asset-source", "input-provided") .attr("data-anchor", "row-card-left-center") .attr("data-collision-rule", "inside row card before label column") .attr("data-no-copied-reference-art", "true") .attr("x", iconX) .attr("y", centerY - flagHeight / 2) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); } else { g.append("circle") .attr("class", "field-icon neutral-placeholder") .attr("data-asset-slot", `field_icon_${String(dimension).replace(/[^a-z0-9]+/gi, "_").toLowerCase()}`) .attr("data-asset-source", "neutral_placeholder") .attr("data-anchor", "row-card-left-center") .attr("data-collision-rule", "inside row card before label column") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("cx", iconX + flagWidth / 2) .attr("cy", centerY) .attr("r", Math.min(flagWidth, flagHeight) / 2) .attr("fill", "#E8F4F1") .attr("stroke", "#BFD9D3") .attr("stroke-width", 1); }
// 添加维度标签(支持多行换行) const labelConfig = dimLabelConfig[dimension]; const labelGroup = g.append("text") .attr("x", labelX) .attr("class", "category-label") .attr("data-relationship", "centerline-aligned-to-row-card-and-icon") .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", 700) .style("fill", labelColor);
if (labelConfig.needsWrapping) { const lineHeight = labelConfig.lineHeight; const startY = centerY - ((labelConfig.lines.length - 1) * lineHeight) / 2; labelGroup.attr("y", startY);
labelConfig.lines.forEach((line, i) => { labelGroup.append("tspan") .attr("x", labelX) .attr("dy", i === 0 ? "0.35em" : `${lineHeight}`) .text(line); }); } else { labelGroup .attr("y", centerY) .attr("dy", "0.35em") .text(labelConfig.lines[0]); } // 添加数值标签 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; g.append("text") .attr("x", barWidth + 10) .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("class", "value-label") .attr("data-relationship", "value-label-floats-after-rounded-bar-end") .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(22,Math.max(barHeight * 0.5, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", 800) .style("fill", valueColor) .text(formattedValue); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_13", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 20], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["radius_corner", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图与比例圆复合图表实现 - 使用D3.jsfunction makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // 1. 数据准备 const jsonData = data; // 完整JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置默认值 title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { text_color: "#FFFFFF", background_color: "#0A3B39", other: { primary: "#83C341" } }; const images = jsonData.images || { field: {}, other: {} }; // 图像配置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 const titles = jsonData.titles || {}; // 标题配置 // 设置视觉效果默认值 variables.has_rounded_corners = variables.has_rounded_corners !== undefined ? variables.has_rounded_corners : true; variables.has_spacing = variables.has_spacing !== undefined ? variables.has_spacing : false; // 清空容器 d3.select(containerSelector).html(""); // 2. 尺寸和布局设置 const width = variables.width || 800; let currentChartHeight = variables.height || 600; // 初始化图表高度,后续可能调整 // 设置边距 const margin = { top: 100, // 顶部标题空间 right: 5, // 右侧边距 bottom: 40, // 底部边距 left: 0 // 左侧边距(条形图紧贴左边) }; // 3. 提取字段名和单位 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : ""; // 列标题 const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 4. 数据处理 const sortedData = [...chartData].sort((a, b) => b[valueField1] - a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // -- 动态调整SVG高度 -- if (sortedDimensions.length > 15) { const excessDimensions = sortedDimensions.length - 15; const percentIncrease = excessDimensions * 0.03; // 每增加一个维度,高度增加3% currentChartHeight = Math.round(currentChartHeight * (1 + percentIncrease)); } // -- 结束动态调整SVG高度 -- // 添加数值格式化函数 // 5. 布局计算 const flagMargin = 10; const textMargin = 5; // 设置条形图和圆形图的布局比例 const leftColumnRatio = 0.85; // 左列占比 const rightColumnRatio = 0.15; // 右列占比 // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = currentChartHeight - margin.top - margin.bottom; // 使用调整后的高度 // 计算两列的宽度 const barChartWidth = innerWidth * leftColumnRatio; const circleChartWidth = innerWidth * rightColumnRatio; // 6. 创建比例尺 const barPadding = variables.has_spacing ? 0.3 : 0.1; // Y轴比例尺(维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(第一个数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, barChartWidth]); // 圆形面积比例尺(第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); const minRadius = yScale.bandwidth() * 0.3; // 最小半径 const maxRadius = Math.min(yScale.bandwidth() * 1.0, circleChartWidth*0.5) // 最大半径 const radiusScale = d3.scaleSqrt() // 使用平方根比例尺确保面积比例正确 .domain([0, maxValue2]) .range([minRadius, maxRadius]); // 新增: 动态计算图标(flag)的尺寸 const barHeightForIconScaling = yScale.bandwidth(); const barHeightThresholdForIcon = 35; // px, 用于切换图标缩放比例的阈值 // 如果条形高度较低,则图标相对条形较大 (80%);如果条形高度较高,则图标相对条形较小 (60%) const iconScaleFactor = barHeightForIconScaling < barHeightThresholdForIcon ? 0.8 : 0.6; // 计算图标尺寸,确保最小为10px,且不超过条形本身的高度 const calculatedFlagSize = Math.min( barHeightForIconScaling, Math.max(10, Math.round(barHeightForIconScaling * iconScaleFactor)) ); const flagWidth = calculatedFlagSize; const flagHeight = calculatedFlagSize; // 7. 创建SVG容器 const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", currentChartHeight) // 使用调整后的高度 .attr("viewBox", `0 0 ${width} ${currentChartHeight}`) // 使用调整后的高度 .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink");
// Define clip path for bars const clipPathId = "bar-clip-path"; svg.append("defs") .append("clipPath") .attr("id", clipPathId) .append("rect") .attr("x", 0) .attr("y", 0) .attr("width", barChartWidth) // Clip at the right edge of the bar area .attr("height", innerHeight);
// 8. 添加标题 const tempTextSvg = svg.append("g").attr("visibility", "hidden");
// ---------- Helper: Estimate Generic Text Width ---------- const estimateGenericTextWidth = (text, fontConfig, tempSvg) => { return chartUtils.text.measure(tempSvg, text, { fontFamily: fontConfig.font_family, fontSize: fontConfig.font_size, fontWeight: fontConfig.font_weight }).width; };
// ---------- Helper: Get Wrapped Lines ---------- function getWrappedLines(textContent, availableWidth, fontConfig, tempSvg) { const words = (textContent || "").trim().split(/\s+/).filter(w => w !== ""); const lines = []; // 使用 parseFloat 解析字体大小(例如 "16px" -> 16),然后乘以1.2作为行高估计 const fontSizeValue = parseFloat(fontConfig.font_size); const lineHeight = fontSizeValue * 1.2;
if (words.length === 0) { return { linesArray: [], numLines: 0, lineHeight: lineHeight }; }
let currentLine = words[0]; for (let i = 1; i < words.length; i++) { const word = words[i]; const testLine = currentLine + " " + word; if (estimateGenericTextWidth(testLine, fontConfig, tempSvg) > availableWidth && currentLine !== "") { lines.push(currentLine); currentLine = word; } else { currentLine = testLine; } } if (currentLine !== "") { lines.push(currentLine); } return { linesArray: lines, numLines: lines.length, lineHeight: lineHeight }; }
const estimateLabelWidth = (text, fontConfig, barHeight) => { // Calculate dynamic font size for value labels if applicable const isValueLabel = fontConfig === typography.annotation; const fontSize = isValueLabel ? `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px` : fontConfig.font_size;
return chartUtils.text.measure(tempTextSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width; };
// ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 8. 添加标题 (重构部分) ---------- const titleFontConfig = typography.description; const titleBottomPadding = 10; // 标题底部与图表顶部���间的间距 const desiredBaselineOfLastLine = margin.top - titleBottomPadding;
// 左侧列标题 const leftTitleAvailableWidth = innerWidth * 0.6; const leftTitleXPos = margin.left; const wrappedLeftTitle = getWrappedLines(columnTitle1, leftTitleAvailableWidth, titleFontConfig, tempTextSvg); if (wrappedLeftTitle.numLines > 0) { const initialYLeft = desiredBaselineOfLastLine - (wrappedLeftTitle.numLines - 1) * wrappedLeftTitle.lineHeight; const leftTitleText = svg.append("text") .attr("x", leftTitleXPos) .attr("y", initialYLeft) .attr("text-anchor", "start") .style("font-family", titleFontConfig.font_family) .style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
wrappedLeftTitle.linesArray.forEach((line, i) => { leftTitleText.append("tspan") .attr("x", leftTitleXPos) .attr("dy", i === 0 ? 0 : wrappedLeftTitle.lineHeight) .text(line); }); }
// 右侧列标题 const rightTitleAvailableWidth = innerWidth * 0.4; const rightTitleXPos = margin.left + innerWidth; // 新的右对齐X坐标 (即:allocated space for left + allocated space for right) const wrappedRightTitle = getWrappedLines(columnTitle2, rightTitleAvailableWidth, titleFontConfig, tempTextSvg);
if (wrappedRightTitle.numLines > 0) { const initialYRight = desiredBaselineOfLastLine - (wrappedRightTitle.numLines - 1) * wrappedRightTitle.lineHeight; const rightTitleText = svg.append("text") .attr("x", rightTitleXPos) .attr("y", initialYRight) .attr("text-anchor", "end") // 右侧标题修改为end对齐 .style("font-family", titleFontConfig.font_family) .style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
wrappedRightTitle.linesArray.forEach((line, i) => { rightTitleText.append("tspan") .attr("x", rightTitleXPos) // tspan也使用相同的X坐标,由text-anchor控制对齐 .attr("dy", i === 0 ? 0 : wrappedRightTitle.lineHeight) .text(line); }); } // ---------- 结束添加标题 ----------
// ---------- 10. 绘制条形和标签 ---------- // 获取条形图颜色 const getBarColor = (dimension) => { return colorResolver.other("primary", { fallback: "#83C341" }).value; // 亮绿色 }; // 获取圆形图颜色 const getCircleColor = (dimension) => { return colorResolver.other("primary", { fallback: "#83C341" }).value; // 亮绿色 };
// 存储第一个条形的宽度,用于后续条形图标签位置决策 let firstBarWidth = 0; if (sortedDimensions.length > 0) { const firstDataPoint = chartData.find(d => d[dimensionField] === sortedDimensions[0]); if (firstDataPoint) { firstBarWidth = xScale(+firstDataPoint[valueField1]); } } // 为每个维度绘制条形和圆形 sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (!dataPoint) { console.error(`No data found for dimension: ${dimension}`); return; } // 检查数据值是否有效 if (isNaN(+dataPoint[valueField1]) || isNaN(+dataPoint[valueField2])) { console.error(`Invalid data values for ${dimension}: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; } const barHeight = yScale.bandwidth(); const y = yScale(dimension); if (typeof y !== 'number') { console.error(`Invalid y position for dimension: ${dimension}`); return; } const centerY = y + barHeight / 2; const barWidthValue = xScale(+dataPoint[valueField1]); const barRadius = barHeight / 2; // 条形图右侧圆角半径
// --- Calculate Element Widths and Spaces --- const iconSize = flagWidth; // 图标大小 const textPadding = 5; // 文本内边距
const dimensionLabelText = dimension.toUpperCase(); const valueLabelText = `${chartUtils.format.autoText(+dataPoint[valueField1])}${valueUnit1}`;
const currentDimLabelWidth = estimateLabelWidth(dimensionLabelText, typography.label, barHeight); const currentValueLabelWidth = estimateLabelWidth(valueLabelText, typography.annotation, barHeight);
const iconMinSpace = iconSize + textPadding; // 仅图标所需空间 const totalIconDimSpace = iconMinSpace + currentDimLabelWidth + textPadding; // 图标+维度标签所需空间 const totalInsideSpace = totalIconDimSpace + currentValueLabelWidth + textPadding * 2; // 所有元素所需空间
// --- Determine Positioning Strategy based on barWidthValue --- let iconX, dimLabelX, valueLabelX; let dimLabelColor, valueLabelColor; let dimLabelAnchor, valueLabelAnchor; let lineStartX; // 连接线起点
if (barWidthValue < iconMinSpace) { // 策略1:所有元素放在外部 iconX = barWidthValue + textPadding; dimLabelX = iconX + iconSize + textPadding; valueLabelX = dimLabelX + currentDimLabelWidth + 15; dimLabelColor = colorResolver.text({ fallback: "#333333" }).value; valueLabelColor = colorResolver.text({ fallback: "#333333" }).value; dimLabelAnchor = "start"; valueLabelAnchor = "start"; lineStartX = valueLabelX + currentValueLabelWidth; } else if (barWidthValue < totalIconDimSpace) { // 策略2:图标内部,文本外部 iconX = textPadding; dimLabelX = barWidthValue + textPadding; valueLabelX = dimLabelX + currentDimLabelWidth + 15; dimLabelColor = colorResolver.text({ fallback: "#333333" }).value; valueLabelColor = colorResolver.text({ fallback: "#333333" }).value; dimLabelAnchor = "start"; valueLabelAnchor = "start"; lineStartX = valueLabelX + currentValueLabelWidth; } else { // 策略3:图标和维度标签内部,检查数值标签 iconX = textPadding; dimLabelX = iconX + iconSize + textPadding; dimLabelColor = colorResolver.text({ fallback: "#333333" }).value; dimLabelAnchor = "start"; if (barWidthValue >= totalInsideSpace) { // 策略3a:所有元素内部 valueLabelX = barWidthValue - textPadding; valueLabelColor = "#FFFFFF"; valueLabelAnchor = "end"; lineStartX = barWidthValue; } else { // 策略3b:数值标签外部 valueLabelX = barWidthValue + textPadding; valueLabelColor = colorResolver.text({ fallback: "#333333" }).value; valueLabelAnchor = "start"; lineStartX = valueLabelX + currentValueLabelWidth; } }
// 1. 绘制条形 (barRadius was defined above) g.append("path") .attr("d", () => { // Always draw the bar with the rounded right corner // The clip path will handle cases where barWidthValue < barRadius const pathData = ` M 0,${y} L ${barWidthValue - barRadius},${y} A ${barRadius},${barRadius} 0 0,1 ${barWidthValue},${centerY} A ${barRadius},${barRadius} 0 0,1 ${barWidthValue - barRadius},${y + barHeight} L 0,${y + barHeight} Z `; return pathData; }) .attr("fill", getBarColor(dimension)) .attr("opacity", 0.9) .attr("clip-path", `url(#${clipPathId})`); // Apply the clip path
// 2. 添加国家/地区标签和图标 (using calculated positions) const iconGroup = g.append("g") .attr("transform", `translate(${iconX}, ${centerY - flagHeight/2})`);
if (images.field && images.field[dimension]) { const clipRadius = (flagHeight/2) * 0.8; const clipId = `clip-${dimension.replace(/\s+/g, '-').toLowerCase()}-${index}`; const defs = g.append("defs"); defs.append("clipPath") .attr("id", clipId) .append("circle") .attr("cx", flagWidth/2) .attr("cy", flagHeight/2) .attr("r", clipRadius - 2); // Border Circle (always add, even if image is missing, for consistency? Maybe not) iconGroup.append("circle") .attr("cx", flagWidth/2) .attr("cy", flagHeight/2) .attr("r", clipRadius) .attr("fill", "none") .attr("stroke", "#000000") // Keep border consistent .attr("stroke-width", 2);
// Clipped Image iconGroup.append("image") .attr("x", 0) .attr("y", 0) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]) .attr("clip-path", `url(#${clipId})`); } // Dimension Label (Country Name) g.append("text") .attr("x", dimLabelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", dimLabelAnchor) .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", dimLabelColor) .text(dimensionLabelText);
// 3. 添加条形数值标签 (Percentage) const valueLabelFontSize = `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`; g.append("text") .attr("x", valueLabelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", valueLabelAnchor) .style("font-family", typography.annotation.font_family) .style("font-size", valueLabelFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", valueLabelColor) .text(valueLabelText);
// 4. 绘制圆形 (Nominal GDP) const circleRadius = radiusScale(+dataPoint[valueField2]); const circleX = barChartWidth + circleChartWidth / 2; g.append("circle") .attr("cx", circleX) .attr("cy", centerY) .attr("r", circleRadius) .attr("fill", getCircleColor(dimension)) .attr("opacity", 0.6);
// 5. 添加圆形数值标签 (GDP Value) const formattedValue2 = `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}`; const circleLabelFontSize = `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`; g.append("text") .attr("x", circleX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", circleLabelFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue2);
// 6. 添加连接线 - using calculated lineStartX const lineColor = colorResolver.available(index, { cycle: true, fallback: colorResolver.other("primary", { fallback: "#83C341" }).value }).value; const lineEndX = circleX - circleRadius;
if (lineStartX < lineEndX - 1) { g.append("line") .attr("x1", lineStartX) .attr("y1", centerY) .attr("x2", lineEndX) .attr("y2", centerY) .attr("stroke", lineColor) .attr("stroke-width", 0.8); } } catch (error) { console.error(`渲染${dimension}时出错:`, error); } });
// 移除临时SVG元素 tempTextSvg.remove();
// 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_14", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": ["primary"], "supported_effects": ["radius_corner", "spacing", "shadow", "gradient", "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*/
// 水平条形图与比例圆复合图表实现 - 使用D3.js horizontal bar proportional circle area chart 02function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置,如果不存在则使用默认值 title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { text_color: "#000000", background_color: "#FFFFFF", other: { primary: "#83C341" } }; const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 const titles = jsonData.titles || {}; // 标题配置 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners !== undefined ? variables.has_rounded_corners : false; variables.has_spacing = variables.has_spacing !== undefined ? variables.has_spacing : false; variables.has_shadow = variables.has_shadow !== undefined ? variables.has_shadow : false; variables.has_gradient = variables.has_gradient !== undefined ? variables.has_gradient : false; variables.has_stroke = variables.has_stroke !== undefined ? variables.has_stroke : false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 100, // 顶部留出标题空间 right: 5, // 右侧边距 bottom: 40, // 底部边距 left: 10 // 左侧边距,给文字留出一些空间 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y", { fallbackKey: "Crypto Ownership Percentage" }).key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : ""; // 列标题(使用数据列的name字段,而不是description) const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // ---------- 4. 数据处理 ---------- // 按第一个数值字段降序排序��据 const sortedData = [...chartData].sort((a, b) => b[valueField1] - a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 // ---------- 5. 布局计算 ---------- // 设置条形图和圆形图的布局比例 const leftColumnRatio = 0.85; // 左列占比 const rightColumnRatio = 0.15; // 右列占比 // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // 计算两列的宽度 const barChartWidth = innerWidth * leftColumnRatio; const circleChartWidth = innerWidth * rightColumnRatio; // ---------- 6. 创建比例尺 ---------- // 计算条形的额外间距(如果启用) const barPadding = variables.has_spacing ? 0.2 : 0.1; // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(用于第一个数值)- 条形图 const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, barChartWidth]); // 圆形面积比例尺(用于第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); const minRadius = yScale.bandwidth() * 0.1; // 最小半径 // 最大半径限制在条形高度的一半和右侧列宽的一半之间取较小值 const maxRadius = Math.min(yScale.bandwidth() * 0.5, circleChartWidth * 0.4); // 稍微缩小一点以防边缘碰撞 const radiusScale = d3.scaleSqrt() // 使用平方根比例尺确保面积比例正确 .domain([0, maxValue2]) .range([minRadius, maxRadius]); // ---------- 7. 创建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"); // ---------- Temporary SVG for text measurement (for titles) ---------- const tempTextSvgForTitles = svg.append("g").attr("visibility", "hidden");
// ---------- Helper: Estimate Generic Text Width (for titles) ---------- const estimateGenericTextWidth_forTitles = (text, fontConfig) => { return chartUtils.text.measure(tempTextSvgForTitles, text, { fontFamily: fontConfig.font_family, fontSize: fontConfig.font_size, fontWeight: fontConfig.font_weight }).width; };
// ---------- Helper: Get Wrapped Lines (for titles) ---------- function getWrappedLines_forTitles(textContent, availableWidth, fontConfig) { const words = (textContent || "").trim().split(/\s+/).filter(w => w !== ""); const lines = []; const fontSizeValue = parseFloat(fontConfig.font_size); const lineHeight = fontSizeValue * 1.2; // Estimate line height
if (words.length === 0) { return { linesArray: [], numLines: 0, lineHeight: lineHeight }; }
let currentLine = words[0]; if (words.length === 1) { if (estimateGenericTextWidth_forTitles(currentLine, fontConfig) > availableWidth) { // Attempt to break the single word if it's too long let tempLine = ""; for (let char of currentLine) { if (estimateGenericTextWidth_forTitles(tempLine + char, fontConfig) > availableWidth && tempLine !== "") { lines.push(tempLine); tempLine = char; } else { tempLine += char; } } if (tempLine !== "") lines.push(tempLine); if (lines.length === 0 && currentLine !== "") lines.push(currentLine); // Fallback for very short availableWidth } else { lines.push(currentLine); } return { linesArray: lines, numLines: lines.length, lineHeight: lineHeight }; }
// For multiple words for (let i = 1; i < words.length; i++) { const word = words[i]; const testLine = currentLine + " " + word; if (estimateGenericTextWidth_forTitles(testLine, fontConfig) > availableWidth && currentLine !== "") { lines.push(currentLine); currentLine = word; } else { currentLine = testLine; } } if (currentLine !== "") { // Add the last line // Check if the last line (which could be a single word) itself needs breaking if (estimateGenericTextWidth_forTitles(currentLine, fontConfig) > availableWidth && !currentLine.includes(" ")) { let tempLine = ""; for (let char of currentLine) { if (estimateGenericTextWidth_forTitles(tempLine + char, fontConfig) > availableWidth && tempLine !== "") { lines.push(tempLine); tempLine = char; } else { tempLine += char; } } if (tempLine !== "") lines.push(tempLine); if (lines.length === 0 && currentLine !== "") lines.push(currentLine); } else if (estimateGenericTextWidth_forTitles(currentLine, fontConfig) > availableWidth && currentLine.includes(" ")) { // Re-process the last line as if it's a new text to wrap (if it's multi-word but still too long) const subWrapped = getWrappedLines_forTitles(currentLine, availableWidth, fontConfig); lines.push(...subWrapped.linesArray); } else { lines.push(currentLine); } }
return { linesArray: lines.filter(l => l.length > 0), numLines: lines.filter(l => l.length > 0).length, lineHeight: lineHeight }; }
// ---------- 8. 添加SVG定义 ---------- // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") // 增加滤镜区域以包含阴影 .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3) // 阴影模糊度 .attr("result", "blur"); filter.append("feOffset") .attr("in", "blur") // 输入为模糊后的图像 .attr("dx", 2) // 水平偏移 .attr("dy", 2) // 垂直偏移 .attr("result", "offsetBlur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode") // 添加阴影层 .attr("in", "offsetBlur"); feMerge.append("feMergeNode") // 添加原始图形层(置于顶层) .attr("in", "SourceGraphic"); } // 为每个维度创建渐变(如果启用) if (variables.has_gradient) { sortedDimensions.forEach(dimension => { const barColor = getBarColor(dimension); const gradient = defs.append("linearGradient") .attr("id", `bar-gradient-${dimension.replace(/\s+/g, '-')}`) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") // 水平渐变 .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(barColor, { mode: "brighter", amount: 0.5 })); // 渐变起始颜色(较亮) gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(barColor, { mode: "darker", amount: 0.3 })); // 渐变结束颜色(较暗) }); } // ---------- 9. 添加标题和标题下的线条 ---------- // 计算标题位置 - Refactored for wrapping const titleFontConfig = typography.description; const titleTextBottomMargin = 15; // Space between title text's last line and the decorative line const decorativeLineY = margin.top - titleTextBottomMargin; // Y position of the decorative line const desiredBaselineOfLastTitleLine = decorativeLineY - 5; // Baseline of the last line of title text (5px above the decorative line) // 左侧列标题 const leftTitleAvailableWidth = innerWidth * 0.6; const leftTitleXPos = margin.left; const columnTitle1Upper = columnTitle1.toUpperCase(); const wrappedLeftTitle = getWrappedLines_forTitles(columnTitle1Upper, leftTitleAvailableWidth, titleFontConfig); if (wrappedLeftTitle.numLines > 0) { const initialYLeft = desiredBaselineOfLastTitleLine - (wrappedLeftTitle.numLines - 1) * wrappedLeftTitle.lineHeight; const leftTitleText = svg.append("text") .attr("x", leftTitleXPos) .attr("y", initialYLeft) .attr("text-anchor", "start") .style("font-family", titleFontConfig.font_family) .style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
wrappedLeftTitle.linesArray.forEach((line, i) => { leftTitleText.append("tspan") .attr("x", leftTitleXPos) .attr("dy", i === 0 ? 0 : wrappedLeftTitle.lineHeight) .text(line); }); }
// 右侧列标题 const rightTitleAvailableWidth = innerWidth * 0.4; const rightTitleXPos = width - margin.right; // Align to the right edge of the chart const columnTitle2Upper = columnTitle2.toUpperCase(); const wrappedRightTitle = getWrappedLines_forTitles(columnTitle2Upper, rightTitleAvailableWidth, titleFontConfig);
if (wrappedRightTitle.numLines > 0) { const initialYRight = desiredBaselineOfLastTitleLine - (wrappedRightTitle.numLines - 1) * wrappedRightTitle.lineHeight; const rightTitleText = svg.append("text") .attr("x", rightTitleXPos) .attr("y", initialYRight) .attr("text-anchor", "end") // Right-align .style("font-family", titleFontConfig.font_family) .style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
wrappedRightTitle.linesArray.forEach((line, i) => { rightTitleText.append("tspan") .attr("x", rightTitleXPos) .attr("dy", i === 0 ? 0 : wrappedRightTitle.lineHeight) .text(line); }); }
// 标题下的黑线 (Adjusted Y position) svg.append("line") .attr("x1", margin.left) .attr("y1", decorativeLineY) .attr("x2", width - margin.right) .attr("y2", decorativeLineY) .attr("stroke", "#000000") .attr("stroke-width", 1.5); // 左侧标题下的三角形 (Adjusted X and Y position) const leftTriangleCenterX = margin.left + leftTitleAvailableWidth / 2; svg.append("polygon") .attr("points", `${leftTriangleCenterX - 6},${decorativeLineY + 1} ${leftTriangleCenterX + 6},${decorativeLineY + 1} ${leftTriangleCenterX},${decorativeLineY + 8}`) .attr("fill", "#000000"); // 右侧标题下的三角形 (Adjusted X and Y position) const rightTriangleCenterX = (margin.left + leftTitleAvailableWidth) + (rightTitleAvailableWidth / 2); svg.append("polygon") .attr("points", `${rightTriangleCenterX - 6},${decorativeLineY + 1} ${rightTriangleCenterX + 6},${decorativeLineY + 1} ${rightTriangleCenterX},${decorativeLineY + 8}`) .attr("fill", "#000000"); // Remove the temporary SVG element for title measurement once done with titles tempTextSvgForTitles.remove();
// ---------- 10. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // 应用边距 // ---------- 11. 获取条形图颜色的辅助函数 ---------- // 获取条形图颜色 const getBarColor = (dimension) => { // 优先使用字段特定颜色 if (colorResolver.field(dimension, 0, { fallbackKey: "primary" }).value) { return colorResolver.field(dimension, 0, { fallbackKey: "primary" }).value; } // 否则使用主要的备用颜色 return colorResolver.other("primary", { fallback: "#83C341" }).value; // 使用可选链和默认值增加健壮性 }; // ---------- 12. 绘制所有圆形(先绘制,以免被条形覆盖,确保阴影等效果完整)---------- // 注意:这里只绘制圆形本身,标签将在后面的循环中添加 sortedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (!dataPoint || isNaN(+dataPoint[valueField2])) return; // 跳过无效数据 const barHeight = yScale.bandwidth(); const y = yScale(dimension); const centerY = y + barHeight / 2; // 绘制圆形(应用视觉效果) const circleRadius = radiusScale(+dataPoint[valueField2]); // 圆心X坐标位于右侧列的中心 const circleX = barChartWidth + circleChartWidth / 2; g.append("circle") .attr("cx", circleX) .attr("cy", centerY) .attr("r", Math.max(0, circleRadius)) // 确保半径不为负 .attr("fill", getBarColor(dimension)) .style("stroke", variables.has_stroke ? colorResolver.variant(getBarColor(dimension), { mode: "darker", amount: 0.5 }) : "none") // 添加描边(如果启用) .style("stroke-width", variables.has_stroke ? 1.5 : 0) // 描边宽度 .style("filter", variables.has_shadow ? "url(#shadow)" : "none"); // 应用阴影(如果启用) }); // ---------- 13. 为每个维度绘制条形、标签和连接线 ---------- // Helper function for text wrapping (can be defined here as it uses measureTextWidth from the loop's scope) function getWrappedLines_local(text, maxWidth, style, getTextWidthFunc) { const words = text.split(/\s+/).filter(w => w.length > 0); const lines = [];
if (words.length === 0) return [""]; // Return an empty string in an array if no words
// Helper to wrap a single word if it's too long const wrapSingleWord = (singleWord) => { const wordLines = []; let currentWordPart = ""; for (let char of singleWord) { if (getTextWidthFunc(currentWordPart + char, style) > maxWidth && currentWordPart !== "") { wordLines.push(currentWordPart); currentWordPart = char; } else { currentWordPart += char; } } if (currentWordPart !== "") wordLines.push(currentWordPart); return wordLines.length > 0 ? wordLines : [singleWord]; // Fallback to original word if wrapping fails };
if (words.length === 1) { if (getTextWidthFunc(words[0], style) > maxWidth) { return wrapSingleWord(words[0]); } else { return [words[0]]; } }
let currentLine = words[0]; // Check if the first word itself is too long if (getTextWidthFunc(currentLine, style) > maxWidth) { const wrappedFirstWordLines = wrapSingleWord(currentLine); lines.push(...wrappedFirstWordLines.slice(0, -1)); currentLine = wrappedFirstWordLines.length > 0 ? wrappedFirstWordLines[wrappedFirstWordLines.length - 1] : ""; if (currentLine === "" && words.length > 1) currentLine = words[1]; // Move to next word if first was fully consumed and broken else if (currentLine === "" && words.length ===1) { lines.push(...wrapSingleWord(words[0])); return lines.filter(l => l!="");}
}
for (let i = 1; i < words.length; i++) { const word = words[i]; // First check if the current word itself is too long if (getTextWidthFunc(word, style) > maxWidth) { if (currentLine !== "") lines.push(currentLine); // Push the line before this long word lines.push(...wrapSingleWord(word)); // Push the wrapped parts of the long word currentLine = ""; // Reset currentLine continue; }
const testLine = currentLine === "" ? word : currentLine + " " + word; if (getTextWidthFunc(testLine, style) > maxWidth && currentLine !== "") { lines.push(currentLine); currentLine = word; } else { currentLine = testLine; } }
if (currentLine !== "") { // Add the last line if (getTextWidthFunc(currentLine, style) > maxWidth && !currentLine.includes(" ") ) { // Single long word as last line lines.push(...wrapSingleWord(currentLine)); } else if (getTextWidthFunc(currentLine, style) > maxWidth && currentLine.includes(" ")) { // Last line has multiple words but still too long (edge case after loop logic) // Re-process the last line as if it's a new text to wrap const subLines = getWrappedLines_local(currentLine, maxWidth, style, getTextWidthFunc); lines.push(...subLines); } else { lines.push(currentLine); } } return lines.filter(l => l !== ""); // Ensure no empty lines } sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (!dataPoint) { console.warn(`No data found for dimension: ${dimension}`); // 使用warn而不是error return; // 继续下一个循环 } // 检查数据值是否有效 if (isNaN(+dataPoint[valueField1]) || isNaN(+dataPoint[valueField2])) { console.warn(`Invalid data values for ${dimension}: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; // 继续下一个循环 } const barHeight = yScale.bandwidth(); const y = yScale(dimension); if (typeof y !== 'number') { // 检查yScale返回是否有效 console.warn(`Invalid y position for dimension: ${dimension}`); return; // 继续下一个循环 } const centerY = y + barHeight / 2; // 条形和圆形的中心Y坐标 const barWidthValue = xScale(+dataPoint[valueField1]); // 计算条形宽度 const labelPadding = 5; // 标签与元素之间的通用内边距/外边距 const labelPaddingInside = 10; // 标签在条形内部时的左右内边距 const countryTextOriginal = dimension; // Keep original case for data, use uppercase for display if needed const value1Text = `${chartUtils.format.autoText(+dataPoint[valueField1])}${valueUnit1}`; // 第一个数值的文本 const value2Text = `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}`; // 第二个数值的文本 // 1. 绘制条形(应用视觉效果) const barFill = variables.has_gradient ? `url(#bar-gradient-${dimension.replace(/\s+/g, '-')})` // 使用渐变填充(如果启用) : getBarColor(dimension); // 使用纯色填充 g.append("rect") .attr("x", 0) .attr("y", y) .attr("width", Math.max(0, barWidthValue)) // 确保宽度不为负 .attr("height", barHeight) .attr("fill", barFill) .attr("rx", variables.has_rounded_corners ? barHeight * 0.2 : 0) // 圆角(如果启用) .attr("ry", variables.has_rounded_corners ? barHeight * 0.2 : 0) // 圆角(如果启用) .style("stroke", variables.has_stroke ? colorResolver.variant(getBarColor(dimension), { mode: "darker", amount: 0.5 }) : "none") // 描边(如果启用) .style("stroke-width", variables.has_stroke ? 1.5 : 0) // 描边宽度 .style("filter", variables.has_shadow ? "url(#shadow)" : "none"); // 阴影(如果启用)
// --- 标签定位逻辑 ---
// Helper to measure text width (already defined in outer scope by user, but ensuring it's clear) const measureTextWidth = (text, style) => { return chartUtils.text.measure(g, text, { fontFamily: style.font_family, fontSize: parseFloat(style.font_size) || style.font_size, fontWeight: style.font_weight }).width; };
// --- Dimension Label (countryText) Processing --- const countryTextForDisplay = countryTextOriginal.toUpperCase(); const maxAllowedDimLabelWidth = innerWidth * 0.3; let finalDimFontSize = parseFloat(typography.label.font_size); let currentDimLabelWidth = measureTextWidth(countryTextForDisplay, { ...typography.label, font_size: `${finalDimFontSize}px` });
if (currentDimLabelWidth > maxAllowedDimLabelWidth) { let tempSize = finalDimFontSize; while (tempSize > 8) { // Min font size 8px tempSize--; const tempWidth = measureTextWidth(countryTextForDisplay, { ...typography.label, font_size: `${tempSize}px` }); if (tempWidth <= maxAllowedDimLabelWidth) { break; } } finalDimFontSize = tempSize; currentDimLabelWidth = measureTextWidth(countryTextForDisplay, { ...typography.label, font_size: `${finalDimFontSize}px` }); }
const finalDimLabelStyle = { ...typography.label, font_size: `${finalDimFontSize}px` };
let dimLabelLines = [countryTextForDisplay]; let dimLabelIsWrapped = false; let dimLabelEffectiveWidth = currentDimLabelWidth; // Width after font reduction
if (currentDimLabelWidth > maxAllowedDimLabelWidth) { // Still too wide, so wrap dimLabelIsWrapped = true; dimLabelLines = getWrappedLines_local(countryTextForDisplay, maxAllowedDimLabelWidth, finalDimLabelStyle, measureTextWidth); // Recalculate effective width based on the longest wrapped line let maxWidthOfWrappedLine = 0; dimLabelLines.forEach(line => { const lineWidth = measureTextWidth(line, finalDimLabelStyle); if (lineWidth > maxWidthOfWrappedLine) maxWidthOfWrappedLine = lineWidth; }); dimLabelEffectiveWidth = maxWidthOfWrappedLine > 0 ? maxWidthOfWrappedLine : maxAllowedDimLabelWidth; // Use measured if available }
let dimLabelX, dimLabelColor, dimLabelAnchor; let dimLabelEndPosX;
if (!dimLabelIsWrapped && barWidthValue >= labelPaddingInside + dimLabelEffectiveWidth + labelPaddingInside) { dimLabelX = labelPaddingInside; dimLabelColor = "#FFFFFF"; dimLabelAnchor = "start"; dimLabelEndPosX = dimLabelX + dimLabelEffectiveWidth; } else { dimLabelX = barWidthValue + labelPadding; dimLabelColor = colorResolver.text({ fallback: "#333333" }).value; dimLabelAnchor = "start"; dimLabelEndPosX = dimLabelX + dimLabelEffectiveWidth; }
// Render Dimension Label const dimLabelLineHeight = parseFloat(finalDimLabelStyle.font_size) * 1.2; const totalDimLabelHeight = dimLabelLines.length * dimLabelLineHeight; const firstDimLineY = centerY - (totalDimLabelHeight / 2) + (dimLabelLineHeight / 2);
const dimTextElement = g.append("text") .attr("y", firstDimLineY) .attr("text-anchor", dimLabelAnchor) .style("font-family", finalDimLabelStyle.font_family) .style("font-size", finalDimLabelStyle.font_size) .style("font-weight", finalDimLabelStyle.font_weight) .style("fill", dimLabelColor);
dimLabelLines.forEach((line, i) => { dimTextElement.append("tspan") .attr("x", dimLabelX) // X is set per tspan for consistent alignment .attr("dy", i === 0 ? 0 : dimLabelLineHeight) .text(line); });
// --- Value 1 Label (Percentage) Processing --- const value1LabelStyle = typography.label; // Assuming value1 uses standard label typography const value1LabelWidth = measureTextWidth(value1Text, value1LabelStyle);
let value1LabelX, value1LabelColor, value1LabelAnchor; let value1LabelEndPos;
// Check if dimension label is effectively inside the bar for positioning value1 const isDimLabelInsideBar = (dimLabelX === labelPaddingInside);
if (isDimLabelInsideBar) { if (barWidthValue >= dimLabelEndPosX + labelPadding + value1LabelWidth + labelPaddingInside) { value1LabelX = barWidthValue - labelPaddingInside; value1LabelColor = "#FFFFFF"; value1LabelAnchor = "end"; value1LabelEndPos = barWidthValue; } else { value1LabelX = barWidthValue + labelPadding; value1LabelColor = colorResolver.text({ fallback: "#333333" }).value; value1LabelAnchor = "start"; value1LabelEndPos = value1LabelX + value1LabelWidth; } } else { value1LabelX = dimLabelEndPosX + labelPadding; value1LabelColor = colorResolver.text({ fallback: "#333333" }).value; value1LabelAnchor = "start"; value1LabelEndPos = value1LabelX + value1LabelWidth; }
// Render Value 1 Label g.append("text") .attr("x", value1LabelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", value1LabelAnchor) .style("font-family", value1LabelStyle.font_family) .style("font-size", value1LabelStyle.font_size) .style("font-weight", value1LabelStyle.font_weight) .style("fill", value1LabelColor) .text(value1Text);
// 4. 添加圆形数值标签 (Value 2) const circleRadius = radiusScale(+dataPoint[valueField2]); // 圆心X坐标在右侧列的中心 const circleX = barChartWidth + circleChartWidth / 2; let value2LabelX, value2LabelY, value2LabelColor, value2LabelAnchor, value2LabelDy; const value2LabelWidth = measureTextWidth(value2Text, typography.label); // Re-measure for value2
// 判断文本宽度是否小于圆的直径 (留一些边距) if (circleRadius * 2 > value2LabelWidth + labelPadding * 2) { // 空间足够,文本放在圆内,白色 value2LabelX = circleX; value2LabelY = centerY; value2LabelColor = "#FFFFFF"; value2LabelAnchor = "middle"; value2LabelDy = "0.35em"; // 垂直居中 } else { // 空间不足,文本放在圆上方,与圆相同颜色 value2LabelX = circleX; value2LabelY = centerY - circleRadius - labelPadding; // 圆顶上方加一点间距 value2LabelColor = getBarColor(dimension); // 使用圆的颜色 value2LabelAnchor = "middle"; value2LabelDy = "0em"; // 基线对齐 // 如果标签放在上方后低于图表顶部标题线,则尝试放在下方 if (value2LabelY - (parseFloat(typography.label.font_size)/2) < -(margin.top - decorativeLineY -10) ){ // -margin.top是g元素的顶部,decorativeLineY是线的位置 value2LabelY = centerY + circleRadius + labelPadding + parseFloat(typography.label.font_size); // 圆底下方加间距和字体高度 value2LabelDy = "0.8em"; // 调整基线使文本看起来在圆下方 } }
g.append("text") .attr("x", value2LabelX) .attr("y", value2LabelY) .attr("dy", value2LabelDy) .attr("text-anchor", value2LabelAnchor) .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", value2LabelColor) .text(value2Text);
// 5. 添加连接线 - 从条形图(或标签)到圆形 const lineColor = getBarColor(dimension); // 线条颜色与条形/圆形一致
// 确定线的起始X坐标:应在数值1标签的右侧结束位置之后 const lineStartX = value1LabelEndPos + labelPadding;
// 计算线的终点X坐标(圆的左边缘) const lineEndX = circleX - circleRadius; // 只有当起始点在结束点左侧时才绘制线 if (lineStartX < lineEndX - 1) { // 减1避免绘制极短的线 // 绘制连接线 g.append("line") .attr("x1", lineStartX) .attr("y1", centerY) .attr("x2", lineEndX) .attr("y2", centerY) .attr("stroke", lineColor) .attr("stroke-width", 0.8); // 线条粗细 } } catch (error) { console.error(`Error rendering chart element for ${dimension}:`, error); // 继续处理下一个元素,而不是停止整个图表渲染 } }); // 返回SVG节点 return svg.node(); }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_15", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary", "secondary"], "supported_effects": ["radius_corner", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图与比例圆复合图表实现 - 使用D3.jsfunction makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 获取实际数据数组 - 处理不同的数据结构形式 let chartData = []; if (Array.isArray(jsonData.data)) { chartData = jsonData.data; } else if (jsonData.data && Array.isArray(jsonData.data.data)) { chartData = jsonData.data.data; } // 提取其他配置 const variables = jsonData.variables || {}; const typography = jsonData.typography || { title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { text_color: "#000000", background_color: "#FFFFFF", other: { primary: "#4269d0", secondary: "#4269d0" }, available_colors: ["#4269d0", "#6cc5b0", "#3ca951", "#ff8ab7", "#a463f2", "#97bbf5"] }; const images = jsonData.images || { field: {}, other: {} }; const dataColumns = chartUtils.schema.columns(jsonData); const titles = jsonData.titles || {}; // 设置视觉效果变量的默认值 variables.has_rounded_corners = false; variables.has_spacing = variables.has_spacing !== undefined ? variables.has_spacing : false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 提取字段名和单位 ---------- // 根据数据列提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : ""; // 列标题 const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // ---------- 3. 数据处理 ---------- // 按第一个数值字段降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField1] - +a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 // ---------- 4. 文本测量 ---------- const labelMeasureOptions = { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }; // 4.2 测量每个标签的宽度并找出最大值 const labelWidths = sortedDimensions.map(d => { return chartUtils.text.measure(null, d.toUpperCase(), labelMeasureOptions).width; }); // 4.3 测量数值标签的最大宽度 const valueWidths = sortedData.map(d => { return chartUtils.text.measure(null, `${chartUtils.format.autoText(+d[valueField1])}${valueUnit1}`, labelMeasureOptions).width; }); // 4.4 测量第二个数值标签的最大宽度 const value2Widths = sortedData.map(d => { return chartUtils.text.measure(null, `${chartUtils.format.autoText(+d[valueField2])}${valueUnit2}`, labelMeasureOptions).width; }); const maxLabelWidth = Math.max(...labelWidths); const maxValueWidth = Math.max(...valueWidths); const maxValue2Width = Math.max(...value2Widths); // ---------- 5. 尺寸和布局设置 ---------- // 图标尺寸 const flagWidth = 24; const flagHeight = 24; const flagMargin = 10; const textIconGap = 10; // 标签文本和图标之间的间距 const valueLabelGap = 5; // 条形和值标签之间的间距 // 基于内容计算合适的图表总宽度 const leftSectionWidth = maxLabelWidth + flagWidth + flagMargin + textIconGap; // 设置图表总尺寸 const minWidth = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 100, // 顶部留出标题空间 right: 20, // 大幅增加右侧边距,确保圆形完全显示 bottom: 60, // 底部边距 left: Math.max(20, leftSectionWidth + 20) // 确保左侧边距足够容纳标签和图标 }; // 计算内部绘图区域尺寸 const innerWidth = minWidth - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // 设置条形图和圆形图的分配比例 - 条形图占更多空间 const barChartRatio = 0.8; const circleChartRatio = 0.2; // 计算条形图的最大宽度,保证值标签显示 const barChartWidth = innerWidth * barChartRatio - maxValueWidth - valueLabelGap; // 计算圆形图部分的宽度 const circleChartWidth = innerWidth * circleChartRatio; // 计算圆形的最大直径,确保不溢出右侧边距 const maxCircleDiameter = Math.min(circleChartWidth * 0.8, 80); // 计算实际总宽度 const width = margin.left + barChartWidth + maxValueWidth + valueLabelGap + circleChartWidth + margin.right; // ---------- 6. 创建比例尺 ---------- // 计算条形的额外间距 const barPadding = variables.has_spacing ? 0.3 : 0.2; // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // 条形高度 const barHeight = yScale.bandwidth(); // X轴比例尺(用于第一个数值)- 条形图 const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, barChartWidth]); // 圆形面积比例尺(用于第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); // 计算最小和最大半径 const minRadius = Math.min(barHeight * 0.4, maxCircleDiameter * 0.2); const maxRadius = Math.min(barHeight * (1 + barPadding/2), maxCircleDiameter/2); const radiusScale = d3.scaleSqrt() .domain([0, maxValue2]) .range([minRadius, maxRadius]); // ---------- 7. 创建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"); // ---------- 8. 添加标题 ---------- // 获取条形图颜色和圆形图颜色用于图例 const barColor = colorResolver.field(valueField1, 0, { fallbackKey: "primary" }).value; const circleColor = colorResolver.field(valueField2, 0, { fallbackKey: "secondary" }).value; // 标题宽度是总宽度的一半 const titleWidth = width / 2; // 设置图例大小和间距 const legendSize = 16; // 图例方块/圆形大小 const legendMargin = 8; // 图例与文本间距 const legendTextOffset = legendSize + legendMargin; // 文本起始位置偏移 // 修改:左侧列标题 - 左对齐,占据图表一半宽度,支持自动换行 const leftTitleGroup = svg.append("g") .attr("transform", `translate(0, ${margin.top - 30})`); // 添加方形图例 leftTitleGroup.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", legendSize) .attr("height", legendSize) .attr("fill", barColor); const leftTitle = leftTitleGroup.append("text") .attr("x", legendTextOffset) // 从图例右侧开始 .attr("y", legendSize / 2) // 垂直居中对齐文本 .attr("dy", "0.35em") .attr("text-anchor", "start") // 左对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value); // 为长文本实现换行 wrapText(leftTitle, columnTitle1, titleWidth - legendTextOffset, 1.2); // 修改:右侧列标题 - 右对齐,占据图表一半宽度,圆形图例位于标题文本左侧 const rightTitleGroup = svg.append("g") .attr("transform", `translate(0, ${margin.top - 30})`); // 首先添加标题文本 - 右对齐到图表右边缘 const rightTitle = rightTitleGroup.append("text") .attr("x", width) // 位于图表最右侧 .attr("y", legendSize / 2) .attr("dy", "0.35em") .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle2); // 测量文本宽度以便正确放置图例 const rightTitleWidth = chartUtils.text.measure(rightTitleGroup, columnTitle2, { fontFamily: typography.description.font_family, fontSize: typography.description.font_size, fontWeight: typography.description.font_weight }).width; // 添加圆形图例 - 位于文本左侧 rightTitleGroup.append("circle") .attr("cx", width - rightTitleWidth - legendMargin - 5) .attr("cy", legendSize / 2) .attr("r", legendSize/2) .attr("fill", circleColor); // 文本换行函数 - 只用于左侧标题,右侧标题现在不需要换行 function wrapText(text, str, width, lineHeight) { const words = str.split(/\s+/).reverse(); let word; let line = []; let lineNumber = 0; const y = text.attr("y"); const dy = parseFloat(text.attr("dy") || 0); const textMeasureOptions = { fontFamily: text.style("font-family") || typography.description.font_family, fontSize: parseFloat(text.style("font-size")) || parseFloat(typography.description.font_size), fontWeight: text.style("font-weight") || typography.description.font_weight }; const measureTextWidth = value => chartUtils.text.measure(null, value, textMeasureOptions).width; let tspan = text.text(null).append("tspan") .attr("x", text.attr("x")) .attr("y", y) .attr("dy", dy + "em"); while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (measureTextWidth(line.join(" ")) > width) { line.pop(); tspan.text(line.join(" ")); line = [word]; tspan = text.append("tspan") .attr("x", text.attr("x")) .attr("y", y) .attr("dy", ++lineNumber * lineHeight + dy + "em") .text(word); } } } // ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制元素 ---------- // 获取条形图颜色 const getBarColor = () => { return colorResolver.field(valueField1, 0, { fallback: colorResolver.other("primary").value }).value; }; // 获取圆形图颜色 const getCircleColor = () => { return colorResolver.field(valueField2, 0, { fallback: colorResolver.other("secondary").value }).value; }; // 为每个维度绘制内容 sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (!dataPoint) { console.error(`No data found for dimension: ${dimension}`); return; } // 检查数据值是否有效 if (isNaN(+dataPoint[valueField1]) || isNaN(+dataPoint[valueField2])) { console.error(`Invalid data values for ${dimension}: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; } const y = yScale(dimension); if (typeof y !== 'number') { console.error(`Invalid y position for dimension: ${dimension}`); return; } const barHeight = yScale.bandwidth(); const centerY = y + barHeight / 2; const barWidthValue = xScale(+dataPoint[valueField1]); // 1. 添加国家/地区名称 - 右对齐 // 标签位置在最左侧,右对齐 const labelX = -flagWidth - flagMargin - textIconGap; g.append("text") .attr("x", labelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension.toUpperCase()); // 2. 添加国家/地区图标 - 修改:直接使用矩形图标 if (images.field && images.field[dimension]) { // 创建一个组来包含图像 const iconGroup = g.append("g") .attr("transform", `translate(${-flagWidth - flagMargin}, ${centerY - flagHeight/2})`); // 直接添加国家/地区图标,不使用圆形裁剪 iconGroup.append("image") .attr("x", 0) .attr("y", 0) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // 3. 绘制条形 - 只使用矩形 g.append("rect") .attr("x", 0) .attr("y", y) .attr("width", barWidthValue) .attr("height", barHeight) .attr("fill", getBarColor()) .attr("opacity", 0.9); // 4. 添加条形数值标签 const formattedValue1 = `${chartUtils.format.autoText(+dataPoint[valueField1])}${valueUnit1}`; g.append("text") .attr("x", barWidthValue + valueLabelGap) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue1); // 5. 计算圆形位置 // 确保圆形居中放置 const circleX = barChartWidth + maxValueWidth + valueLabelGap + circleChartWidth / 2; const circleRadius = radiusScale(+dataPoint[valueField2]); // 绘制圆形 g.append("circle") .attr("cx", circleX) .attr("cy", centerY) .attr("r", circleRadius) .attr("fill", getCircleColor()) .attr("opacity", 0.7); // 6. 添加圆形数值标签 const formattedValue2 = `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}`; g.append("text") .attr("x", circleX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue2); } catch (error) { console.error(`Error rendering chart element for ${dimension}:`, error); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_15_hand", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 15], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary", "secondary"], "supported_effects": ["radius_corner", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图与比例圆复合图表实现 - 使用D3.jsfunction makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 获取实际数据数组 - 处理不同的数据结构形式 let chartData = []; if (Array.isArray(jsonData.data)) { chartData = jsonData.data; } else if (jsonData.data && Array.isArray(jsonData.data.data)) { chartData = jsonData.data.data; } // 提取其他配置 const variables = jsonData.variables || {}; const typography = jsonData.typography || { title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { text_color: "#000000", background_color: "#FFFFFF", other: { primary: "#4269d0", secondary: "#4269d0" }, available_colors: ["#4269d0", "#6cc5b0", "#3ca951", "#ff8ab7", "#a463f2", "#97bbf5"] }; const images = jsonData.images || { field: {}, other: {} }; const dataColumns = chartUtils.schema.columns(jsonData); const titles = jsonData.titles || {}; // 设置视觉效果变量的默认值 variables.has_rounded_corners = false; variables.has_spacing = variables.has_spacing !== undefined ? variables.has_spacing : false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 提取字段名和单位 ---------- // 根据数据列提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : ""; // 列标题 const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // ---------- 3. 数据处理 ---------- // 按第一个数值字段降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField1] - +a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 // ---------- 4. 文本测量 ---------- const labelMeasureOptions = { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }; // 4.2 测量每个标签的宽度并找出最大值 const labelWidths = sortedDimensions.map(d => { return chartUtils.text.measure(null, d.toUpperCase(), labelMeasureOptions).width; }); // 4.3 测量数值标签的最大宽度 const valueWidths = sortedData.map(d => { return chartUtils.text.measure(null, `${chartUtils.format.autoText(+d[valueField1])}${valueUnit1}`, labelMeasureOptions).width; }); // 4.4 测量第二个数值标签的最大宽度 const value2Widths = sortedData.map(d => { return chartUtils.text.measure(null, `${chartUtils.format.autoText(+d[valueField2])}${valueUnit2}`, labelMeasureOptions).width; }); const maxLabelWidth = Math.max(...labelWidths); const maxValueWidth = Math.max(...valueWidths); const maxValue2Width = Math.max(...value2Widths); // ---------- 5. 尺寸和布局设置 ---------- // 图表尺寸 const minWidth = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 120, // 顶部留出标题空间 right: 20, // 右侧边距 bottom: 60, // 底部边距 left: 20 // 初始左侧边距 }; // 计算条形高度相关参数 const MAX_BAR_HEIGHT = 100; // 新增:限制条形最大高度为100px // 计算内部绘图区域尺寸 const innerWidth = minWidth - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // 设置条形图和圆形图的分配比例 - 条形图占更多空间 const barChartRatio = 0.8; const circleChartRatio = 0.2; // 计算条形图的最大宽度,保证值标签显示 const barChartWidth = innerWidth * barChartRatio - maxValueWidth - 5; // 计算圆形图部分的宽度 const circleChartWidth = innerWidth * circleChartRatio; // ---------- 6. 创建比例尺 ---------- // 计算条形的额外间距 const barPadding = variables.has_spacing ? 0.3 : 0.2; // 根据数据项数量和最大条形高度计算实际条形高度 const itemCount = sortedDimensions.length; const totalBarSpace = innerHeight * (1 - barPadding); // 考虑间距后可用的总空间 let barHeight = totalBarSpace / itemCount; // 初始计算的每个条形高度 // 限制条形最大高度 barHeight = Math.min(barHeight, MAX_BAR_HEIGHT); // 重新计算总图表高度(如果条形高度被限制) const adjustedInnerHeight = barHeight * itemCount / (1 - barPadding); const adjustedHeight = adjustedInnerHeight + margin.top + margin.bottom; // Y轴比例尺(用于维度)- 使用固定条形高度 const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, adjustedInnerHeight]) .padding(barPadding); // 获取实际的条形高度 const actualBarHeight = yScale.bandwidth(); // 计算图标尺寸 - 新增:根据条形高度动态调整图标大小 const flagHeight = Math.min(64, actualBarHeight - 8); const flagWidth = flagHeight; // 保持图标宽高相等 const flagMargin = 10; const textIconGap = 10; // 标签文本和图标之间的间距 const valueLabelGap = 5; // 条形和值标签之间的间距 // 基于内容计算合适的图表总宽度 const leftSectionWidth = maxLabelWidth + flagWidth + flagMargin + textIconGap; // 更新左侧边距 margin.left = Math.max(20, leftSectionWidth + 20); // 计算圆形的最大直径,确保不溢出右侧边距 const maxCircleDiameter = Math.min(circleChartWidth * 0.8, 80); // 计算实际总宽度 const width = margin.left + barChartWidth + maxValueWidth + valueLabelGap + circleChartWidth + margin.right; // X轴比例尺(用于第一个数值)- 条形图 const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, barChartWidth]); // 圆形面积比例尺(用于第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); // 计算最小和最大半径 const minRadius = Math.min(actualBarHeight * 0.4, maxCircleDiameter * 0.2); const maxRadius = Math.min(actualBarHeight * (1 + barPadding/2), maxCircleDiameter/2); const radiusScale = d3.scaleSqrt() .domain([0, maxValue2]) .range([minRadius, maxRadius]); // ---------- 7. 创建SVG容器 ---------- const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", adjustedHeight) // 使用调整后的高度 .attr("viewBox", `0 0 ${width} ${adjustedHeight}`) // 使用调整后的视图框 .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); // ---------- 8. 添加标题 ---------- // 获取条形图颜色和圆形图颜色用于图例 const barColor = colorResolver.field(valueField1, 0, { fallbackKey: "primary" }).value; const circleColor = colorResolver.field(valueField2, 0, { fallbackKey: "secondary" }).value; // 标题宽度是总宽度的一半 const titleWidth = width / 2; // 设置图例大小和间距 const legendSize = 28.8; // 图例方块/圆形大小,原来16的1.8倍 const legendMargin = 8; // 图例与文本间距 const legendTextOffset = legendSize + legendMargin; // 文本起始位置偏移 // 修改:左侧列标题 - 左对齐,占据图表一半宽度,支持自动换行 const leftTitleGroup = svg.append("g") .attr("transform", `translate(0, ${margin.top - 30})`); // 添加方形图例 leftTitleGroup.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", legendSize) .attr("height", legendSize) .attr("fill", barColor); const leftTitle = leftTitleGroup.append("text") .attr("x", legendTextOffset) // 从图例右侧开始 .attr("y", legendSize / 2) // 垂直居中对齐文本 .attr("dy", "0.35em") .attr("text-anchor", "start") // 左对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value); // 为长文本实现换行 wrapText(leftTitle, columnTitle1, titleWidth - legendTextOffset, 1.2); // 修改:右侧列标题 - 右对齐,占据图表一半宽度,圆形图例位于标题文本左侧 const rightTitleGroup = svg.append("g") .attr("transform", `translate(0, ${margin.top - 30})`); // 首先添加标题文本 - 右对齐到图表右边缘 const rightTitle = rightTitleGroup.append("text") .attr("x", width) // 位于图表最右侧 .attr("y", legendSize / 2) .attr("dy", "0.35em") .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle2); // 测量文本宽度以便正确放置图例 const rightTitleWidth = chartUtils.text.measure(rightTitleGroup, columnTitle2, { fontFamily: typography.description.font_family, fontSize: typography.description.font_size, fontWeight: typography.description.font_weight }).width; // 添加圆形图例 - 位于文本左侧 rightTitleGroup.append("circle") .attr("cx", width - rightTitleWidth - legendMargin - 5) .attr("cy", legendSize / 2) .attr("r", legendSize/2) .attr("fill", circleColor); // 文本换行函数 - 只用于左侧标题,右侧标题现在不需要换行 function wrapText(text, str, width, lineHeight) { const words = str.split(/\s+/).reverse(); let word; let line = []; let lineNumber = 0; const y = text.attr("y"); const dy = parseFloat(text.attr("dy") || 0); const textMeasureOptions = { fontFamily: text.style("font-family") || typography.description.font_family, fontSize: parseFloat(text.style("font-size")) || parseFloat(typography.description.font_size), fontWeight: text.style("font-weight") || typography.description.font_weight }; const measureTextWidth = value => chartUtils.text.measure(null, value, textMeasureOptions).width; let tspan = text.text(null).append("tspan") .attr("x", text.attr("x")) .attr("y", y) .attr("dy", dy + "em"); while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (measureTextWidth(line.join(" ")) > width) { line.pop(); tspan.text(line.join(" ")); line = [word]; tspan = text.append("tspan") .attr("x", text.attr("x")) .attr("y", y) .attr("dy", ++lineNumber * lineHeight + dy + "em") .text(word); } } } // ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制元素 ---------- // 获取条形图颜色 const getBarColor = () => { return colorResolver.field(valueField1, 0, { fallback: colorResolver.other("primary").value }).value; }; // 获取圆形图颜色 const getCircleColor = () => { return colorResolver.field(valueField2, 0, { fallback: colorResolver.other("secondary").value }).value; }; // 为每个维度绘制内容 sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (!dataPoint) { console.error(`No data found for dimension: ${dimension}`); return; } // 检查数据值是否有效 if (isNaN(+dataPoint[valueField1]) || isNaN(+dataPoint[valueField2])) { console.error(`Invalid data values for ${dimension}: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; } const y = yScale(dimension); if (typeof y !== 'number') { console.error(`Invalid y position for dimension: ${dimension}`); return; } const centerY = y + actualBarHeight / 2; const barWidthValue = xScale(+dataPoint[valueField1]); // 1. 添加国家/地区名称 - 右对齐 // 标签位置在最左侧,右对齐 const labelX = -flagWidth - flagMargin - textIconGap; g.append("text") .attr("x", labelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension.toUpperCase()); // 2. 添加国家/地区图标 - 修改:使用动态大小的图标 if (images.field && images.field[dimension]) { // 创建一个组来包含图像 const iconGroup = g.append("g") .attr("transform", `translate(${-flagWidth - flagMargin}, ${centerY - flagHeight/2})`); // 添加国家/地区图标 iconGroup.append("image") .attr("x", 0) .attr("y", 0) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // 3. 绘制条形 - 只使用矩形 g.append("rect") .attr("x", 0) .attr("y", y) .attr("width", barWidthValue) .attr("height", actualBarHeight) .attr("fill", getBarColor()) .attr("opacity", 0.9); // 4. 添加条形数值标签 const formattedValue1 = `${chartUtils.format.autoText(+dataPoint[valueField1])}${valueUnit1}`; g.append("text") .attr("x", barWidthValue + valueLabelGap) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue1); // 5. 计算圆形位置 // 确保圆形居中放置 const circleX = barChartWidth + maxValueWidth + valueLabelGap + circleChartWidth / 2; const circleRadius = radiusScale(+dataPoint[valueField2]); // 绘制圆形 g.append("circle") .attr("cx", circleX) .attr("cy", centerY) .attr("r", circleRadius) .attr("fill", getCircleColor()) .attr("opacity", 0.7); // 6. 添加圆形数值标签 const formattedValue2 = `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}`; g.append("text") .attr("x", circleX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue2); } catch (error) { console.error(`Error rendering chart element for ${dimension}:`, error); } }); const roughness = 1; const bowing = 2; const fillStyle = "solid"; const randomize = false; const pencilFilter = false; const svgConverter = new svg2roughjs.Svg2Roughjs(containerSelector); svgConverter.pencilFilter = pencilFilter; svgConverter.randomize = randomize; svgConverter.svg = svg.node(); svgConverter.roughConfig = { bowing, roughness, fillStyle }; svgConverter.sketch(); // Remove the first SVG element if it exists const firstSvg = document.querySelector(`${containerSelector} svg`); if (firstSvg) { firstSvg.remove(); } // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_16", "is_composite": false, "required_fields": ["x", "y", "group"], "required_fields_type": [["categorical"], ["numerical"], ["categorical"]], "required_fields_range": [[5, 20], [0, "inf"], [2, 6]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": ["group"], "hierarchy":["group"], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "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) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data; // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ----------
// 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600;
// ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名称 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; const groupField = chartUtils.schema.channel(jsonData, "group").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; let groupUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; }
if (chartUtils.schema.channel(jsonData, "group").unit !== "none") { groupUnit = chartUtils.schema.channel(jsonData, "group").unit; } // ---------- 4. 数据处理 ---------- // 获取唯一维度值 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数
// 计算图标尺寸 const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
// 智能换行 const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; }; // ---------- 5. 计算标签宽度 ----------
// 设置边距 const margin = { top: 90, right: 60, bottom: 60, left: 80 }; const innerHeight = height - margin.top - margin.bottom;
// 计算条形的额外间距 const barPadding = variables.has_spacing ? 0.3 : 0.2;
// 创建初始 yScale 来计算 barHeight const yScaleTemp = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
const barHeight = yScaleTemp.bandwidth(); const barGap = Math.max(0, yScaleTemp.step() - yScaleTemp.bandwidth()); const maxDimLabelHeight = barHeight + barGap;
// 定义圆形间距 let circleRadius = barHeight / 2; const circlePadding = 10;
// 使用 buildDimLabelLayout 计算维度标签布局 const dimLabelMaxWidth = width * 0.3; const dimLabelLineSpacing = 1.2;
const dimLabelLayout = buildDimLabelLayout({ containerSelector: containerSelector, labels: sortedDimensions, fontConfig: typography.label, maxWidth: dimLabelMaxWidth, maxHeight: maxDimLabelHeight, lineSpacing: dimLabelLineSpacing, targetFontSize: Math.min(30, barHeight * 0.6) });
const dimLabelConfig = dimLabelLayout.dimLabelConfig; const maxLabelWidth = dimLabelLayout.maxLabelWidth;
// 创建临时SVG来测量数值标签宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
// 计算最大数值标签宽度 let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`;
const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: Math.min(30, Math.max(12, barHeight * 0.6)), fontWeight: typography.annotation.font_weight }).width;
maxValueWidth = Math.max(maxValueWidth, textWidth); });
// 删除临时SVG tempSvg.remove();
// 根据标签宽度调整左右边距 const totalLabelWidth = (circleRadius * 2) + circlePadding + maxLabelWidth; margin.left = Math.max(margin.left, totalLabelWidth + 20); margin.right = Math.max(margin.right, maxValueWidth + 20); // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; // ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 为每个组添加不同的渐变(如果启用) if (variables.has_gradient) { // 获取所有唯一的组值 const uniqueGroups = [...new Set(chartData.map(d => d[groupField]))]; uniqueGroups.forEach(group => { const groupColor = colorResolver.field(group, 0, { fallbackKey: "primary" }).value || "#882e2e"; const gradient = defs.append("linearGradient") .attr("id", `bar-gradient-${group.replace(/\s+/g, '-')}`) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(groupColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(groupColor, { mode: "darker", amount: 0.3 })); }); }
// ---------- 7. 创建比例尺 ----------
// X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) .range([0, innerWidth]);
// ---------- 8. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 9. 绘制条形和标签 ---------- // 获取条形颜色的辅助函数 - 基于组值而不是索引 const getBarColor = (dataPoint) => { // 如果定义了字段颜色,使用它们 if (colorResolver.field(dataPoint[groupField], 0, { fallbackKey: "primary" }).value) { return colorResolver.field(dataPoint[groupField], 0, { fallbackKey: "primary" }).value; } // 否则使用主要颜色 return colorResolver.other("primary", { fallback: "#882e2e" }).value; }; // 获取渐变ID的辅助函数 const getGradientId = (dataPoint) => { return `url(#bar-gradient-${dataPoint[groupField].replace(/\s+/g, '-')})`; }; // 获取描边颜色的辅助函数 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.available(0, { fallback: "#333333" }).value; };
// 为每个维度绘制条形和标签 sortedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension);
if (dataPoint) { const yPos = yScaleTemp(dimension); const centerY = yPos + barHeight / 2; const barWidth = xScale(+dataPoint[valueField]);
// 计算圆形序号位置 const circleX = -circleRadius * 2 - circlePadding; const circleY = centerY;
// 绘制条形,从圆心开始 g.append("rect") .attr("x", circleX) .attr("y", yPos) .attr("width", barWidth + Math.abs(circleX)) .attr("height", barHeight) .attr("fill", variables.has_gradient ? getGradientId(dataPoint) : getBarColor(dataPoint)) .attr("rx", variables.has_rounded_corners ? 3 : 0) .attr("ry", variables.has_rounded_corners ? 3 : 0) .style("stroke", variables.has_stroke ? getStrokeColor() : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); });
// 绘制黑色圆形 g.append("circle") .attr("cx", circleX) .attr("cy", circleY) .attr("r", circleRadius) .attr("fill", "#000000");
// 添加白色序号 g.append("text") .attr("x", circleX) .attr("y", circleY) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", `${barHeight * 0.5}px`) .style("font-weight", "bold") .style("fill", "#FFFFFF") .text(index + 1);
// 添加维度标签(支持多行换行) const labelConfig = dimLabelConfig[dimension]; const labelX = circleX - circleRadius - 5; const labelGroup = g.append("text") .attr("x", labelX) .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
if (labelConfig.needsWrapping) { const lineHeight = labelConfig.lineHeight; const startY = centerY - ((labelConfig.lines.length - 1) * lineHeight) / 2; labelGroup.attr("y", startY);
labelConfig.lines.forEach((line, i) => { labelGroup.append("tspan") .attr("x", labelX) .attr("dy", i === 0 ? "0.35em" : `${lineHeight}`) .text(line); }); } else { labelGroup .attr("y", centerY) .attr("dy", "0.35em") .text(labelConfig.lines[0]); } // 添加数值标签 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`;
const valueColor = variables.has_gradient ? getBarColor(dataPoint) : getBarColor(dataPoint);
g.append("text") .attr("x", circleX + barWidth + Math.abs(circleX) + 5) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(30, Math.max(12, barHeight * 0.6))}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", valueColor) .text(formattedValue); } });
// ---------- 10. 改进图例 ---------- const uniqueGroups = [...new Set(chartData.map(d => d[groupField]))]; if (uniqueGroups.length > 1) { // 创建新的临时SVG用于测量图例文本宽度 const legendTempSvg = svg.append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden"); // 计算每个图例项的宽度 const legendItemPadding = 10; const legendItemHeight = 20; // 图例项高度 const legendItemMargin = 10; // 图例项之间的间距 // 计算图例可用的最大宽度(60%的图表宽度) const maxLegendWidth = width * 0.6; // 存储每个图例项的宽度和文本 const legendItems = []; uniqueGroups.forEach(group => { const textWidth = chartUtils.text.measure(legendTempSvg, group, { fontFamily: typography.annotation.font_family, fontSize: Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size))), fontWeight: typography.annotation.font_weight }).width; // 计算整个图例项的宽度 (文本宽度 + 内边距 + 矩形宽度) const itemWidth = textWidth + legendItemPadding * 2; legendItems.push({ group: group, width: itemWidth, textWidth: textWidth }); }); // 删除临时SVG legendTempSvg.remove(); chartUtils.legend.inlineTags(svg, legendItems.map(item => ({ label: item.label, color: item.color })), {}, { x: margin.left, y: actualLegendGroupTranslateY, maxWidth: maxLegendWidth, itemHeight: legendItemHeight, itemGap: legendItemMargin, rowGap: 5, itemPadding: legendItemPadding, fontSize: typography.label.font_size, fontFamily: typography.label.font_family, fontWeight: typography.label.font_weight, textColor: colorResolver.text({ fallback: "#333333" }).value, }); } // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_17", "is_composite": false, "required_fields": ["x", "y", "group"], "required_fields_type": [["categorical"], ["numerical"], ["categorical"]], "hierarchy":["group"], "required_fields_range": [[2, 20], [0, "inf"], [2, 5]], "required_fields_icons": ["group"], "required_other_icons": [], "required_fields_colors": ["group"], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data; // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 90, // 顶部留出标题空间 right: 60, // 右侧足够显示数值 bottom: 60, // 底部边距 left: 0 // 左侧初始空间,后续会根据标签长度调整 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名称 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; const groupField = chartUtils.schema.channel(jsonData, "group").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; let groupUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; }
if (chartUtils.schema.channel(jsonData, "group").unit !== "none") { groupUnit = chartUtils.schema.channel(jsonData, "group").unit; } // ---------- 4. 数据处理 ---------- // 获取唯一维度值 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 按数值从小到大排序数据 const sortedData = [...chartData].sort((a, b) => +a[valueField] - +b[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数
// 根据条形高度计算icon尺寸 const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
// 智能换行:优先按单词;利用率不足50%时尝试塞字母;长词断行加"-";断词后下一行单字母开头尽量回并 const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; };
// ---------- 5. 计算标签宽度和图标尺寸 ----------
const textPadding = 10; const maxIconSize = 30; const barPadding = 0.2; const dimLabelMaxWidth = width * 0.2; const dimLabelLineSpacing = 1.01;
const innerHeight = height - margin.top - margin.bottom; const yScaleTemp = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
const barHeight = yScaleTemp.bandwidth(); const barGap = Math.max(0, yScaleTemp.step() - yScaleTemp.bandwidth()); const maxDimLabelHeight = barHeight + barGap;
const iconSize = calcIconSize(barHeight, { maxSize: maxIconSize, minRatio: 0.8, minPx: 10 }); const flagWidth = iconSize.width; const flagHeight = iconSize.height;
const dimLabelLayout = buildDimLabelLayout({ containerSelector: containerSelector, labels: sortedDimensions, fontConfig: typography.label, maxWidth: dimLabelMaxWidth, maxHeight: maxDimLabelHeight, lineSpacing: dimLabelLineSpacing, targetFontSize: Math.min(20, barHeight * 0.6) }); const dimLabelConfig = dimLabelLayout.dimLabelConfig; const maxDimLabelWidth = dimLabelLayout.maxLabelWidth;
const requiredLeftSpace = maxDimLabelWidth + textPadding + flagWidth + textPadding; margin.left = requiredLeftSpace + 5;
const innerWidth = width - margin.left - margin.right; // ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 获取所有唯一的组值 const uniqueGroups = [...new Set(chartData.map(d => d[groupField]))]; // 为每个组��加不同的渐变(如果启用) if (variables.has_gradient) { uniqueGroups.forEach(group => { const groupColor = colorResolver.field(group, 0, { fallbackKey: "primary" }).value || "#4682B4"; const gradient = defs.append("linearGradient") .attr("id", `bar-gradient-${group.replace(/\s+/g, '-')}`) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(groupColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(groupColor, { mode: "darker", amount: 0.3 })); }); } // ---------- 7. 创建比例尺 ----------
// Y轴比例尺(用于维度) const yScale = yScaleTemp;
// X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) .range([0, innerWidth]); // ---------- 8. 创建主图表组 ----------
const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 9. 绘制条形和标签 ---------- // 获取条形颜色的辅助函数 const getBarColor = (dataPoint) => { // 如果定义了字段颜色,使用它们 if (colorResolver.field(dataPoint[groupField], 0, { fallbackKey: "primary" }).value) { return colorResolver.field(dataPoint[groupField], 0, { fallbackKey: "primary" }).value; } // 否则使用主要颜色 return colorResolver.other("primary", { fallback: "#4682B4" }).value; }; // 获取渐变ID的辅助函数 const getGradientId = (dataPoint) => { return `url(#bar-gradient-${dataPoint[groupField].replace(/\s+/g, '-')})`; }; // 获取描边颜色的辅助函数 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.available(0, { fallback: "#333333" }).value; }; // 为每个维度绘制条形和标签 sortedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension);
if (dataPoint) { const barHeight = yScale.bandwidth(); const y = yScale(dimension); const centerY = y + barHeight / 2; const barWidthValue = Math.max(0, xScale(+dataPoint[valueField]));
const labelX = -(flagWidth + textPadding + 5); const iconX = -flagWidth - 5;
// 绘制条形 g.append("rect") .attr("x", 0) .attr("y", y) .attr("width", barWidthValue) .attr("height", barHeight) .attr("fill", variables.has_gradient ? getGradientId(dataPoint) : getBarColor(dataPoint)) .attr("rx", variables.has_rounded_corners ? 3 : 0) .attr("ry", variables.has_rounded_corners ? 3 : 0) .style("stroke", variables.has_stroke ? getStrokeColor() : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none");
// 添加维度标签(支持多行换行) const labelConfig = dimLabelConfig[dimension]; const labelGroup = g.append("text") .attr("x", labelX) .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
if (labelConfig.needsWrapping) { const lineHeight = labelConfig.lineHeight; const startY = centerY - ((labelConfig.lines.length - 1) * lineHeight) / 2; labelGroup.attr("y", startY);
labelConfig.lines.forEach((line, i) => { labelGroup.append("tspan") .attr("x", labelX) .attr("dy", i === 0 ? "0.35em" : `${lineHeight}`) .text(line); }); } else { labelGroup .attr("y", centerY) .attr("dy", "0.35em") .text(labelConfig.lines[0]); }
// 添加图标 const groupIconUrl = jsonData.images && jsonData.images.field && jsonData.images.field[dataPoint[groupField]] ? jsonData.images.field[dataPoint[groupField]] : null;
const iconGroup = g.append("g") .attr("transform", `translate(${iconX}, ${centerY - flagHeight/2})`);
if (groupIconUrl) { iconGroup.append("image") .attr("x", 0) .attr("y", 0) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", groupIconUrl); } else { iconGroup.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", flagWidth) .attr("height", flagHeight) .attr("fill", getBarColor(dataPoint)) .attr("rx", variables.has_rounded_corners ? 3 : 0) .attr("ry", variables.has_rounded_corners ? 3 : 0); }
// 添加条形数值标签 const valueLabel = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`;
const textSize = Math.min(20, Math.max(barHeight * 0.5, parseFloat(typography.annotation.font_size))); const internalPadding = 10; const externalPadding = 5;
let valueLabelXPos, valueLabelAnchor, valueLabelFill;
const currentValueLabelWidth = chartUtils.text.measure(svg, valueLabel, { fontFamily: typography.annotation.font_family, fontSize: textSize, fontWeight: typography.annotation.font_weight }).width;
if (barWidthValue >= currentValueLabelWidth + internalPadding * 2) { valueLabelXPos = internalPadding; valueLabelAnchor = "start"; valueLabelFill = "#FFFFFF"; } else { valueLabelXPos = barWidthValue + externalPadding; valueLabelAnchor = "start"; valueLabelFill = colorResolver.text({ fallback: "#333333" }).value; }
g.append("text") .attr("x", valueLabelXPos) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", valueLabelAnchor) .style("font-family", typography.annotation.font_family) .style("font-size", `${textSize}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", valueLabelFill) .text(valueLabel); } }); // ---------- 10. 添加图例 ---------- // 计算图例位置和大小 const legendRectSize = 16; const legendSpacing = 8; const legendTextSize = parseFloat(typography.annotation.font_size) || 12; const legendPadding = 20; // 计算每组图例的宽度(使用临时元素来计算文本宽度) const tempSvgLegend = svg.append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden"); let legendItemWidths = []; let totalLegendWidth = 0; uniqueGroups.forEach(group => { const groupLabel = groupUnit ? `${group}${groupUnit}` : `${group}`; const textWidth = chartUtils.text.measure(tempSvgLegend, groupLabel, { fontFamily: typography.annotation.font_family, fontSize: legendTextSize, fontWeight: typography.annotation.font_weight }).width; const itemWidth = legendRectSize + legendSpacing + textWidth + legendPadding; legendItemWidths.push(itemWidth); totalLegendWidth += itemWidth; }); tempSvgLegend.remove(); const legendItems = uniqueGroups.map(group => ({ value: group, label: groupUnit ? `${group}${groupUnit}` : `${group}`, color: variables.has_gradient ? `url(#bar-gradient-${String(group).replace(/\s+/g, '-') })` : (colorResolver.field(group, 0, { fallbackKey: "primary" }).value || "#4682B4"), })); chartUtils.legend.centered(svg, legendItems, {}, width / 2, height - margin.bottom / 2, { markerShape: "rect", markerSize: legendRectSize, labelGap: legendSpacing, itemGap: legendPadding, fontSize: legendTextSize, fontFamily: typography.annotation.font_family, fontWeight: typography.annotation.font_weight, textColor: colorResolver.text({ fallback: "#333333" }).value, markerRadius: variables.has_rounded_corners ? 2 : 0, }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356/* REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_18", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": ["primary"], "supported_effects": [], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.js (样式02): horizontal_bar_chart_10function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333", other: { primary: "#0099ff" } // 默认使用蓝色作为条形颜色 }; const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 获取图标数据 const images = jsonData.images || {}; // 设置视觉效果变量 - 根据需求,删除留白、阴影和圆角等效果 variables.has_rounded_corners = false; variables.has_shadow = false; variables.has_gradient = true; // 强制开启渐变 variables.has_stroke = false; variables.has_spacing = false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const originalHeight = variables.height || 600; // 设置边距 - 这个样式需要更多的上部和下部空间用于标签 const margin = { top: 90, // 顶部边距 right: 40, // 右侧足够显示数值标签 bottom: 60, // 底部边距 left: 30 // 左侧边距 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; // 默认为百分比 if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ---------- // 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 按数值降序排序数据(与图片相符) const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 // ---------- 5. 计算标签宽度、动态高度和图表尺寸 ---------- // 动态调整高度 const numDimensions = sortedDimensions.length; let adjustedHeight = originalHeight; const maxHeightFactor = 1.88; if (numDimensions > 18) { // 根据条目数量比例计算建议高度 const suggestedHeight = originalHeight * (numDimensions / 18); // 限制最大高度 adjustedHeight = Math.min(suggestedHeight, originalHeight * maxHeightFactor); } // 使用调整后的高度 const height = adjustedHeight; // 创建临时SVG来测量文本宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden"); // 计算最大维度标签宽度 let maxLabelWidth = 0; dimensions.forEach(dimension => { // 格式化维度名称(附加单位,如果有) const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; const textWidth = chartUtils.text.measure(tempSvg, formattedDimension, { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }).width; maxLabelWidth = Math.max(maxLabelWidth, textWidth); }); // 计算最大数值标签宽度 let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`; const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width; maxValueWidth = Math.max(maxValueWidth, textWidth); }); // 删除临时SVG tempSvg.remove(); // 根据标签宽度调整右边距 margin.right = Math.max(margin.right, maxValueWidth + 10); // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // ---------- 7. 创建比例尺 ---------- // 计算条形的额外间距(取消留白) const barPadding = 0.55; // 设置适当的间距以确保有足够空间放置标签和图标 // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.1]) // 添加10%边距 .range([0, innerWidth]); // 确保小值仍然可见 - 设置最小宽度为0,确保严格按比例绘制 const getBarWidth = (value) => { return xScale(value); }; // ---------- 8. 自适应图标和字体大小计算 ----------
// 计算条形之间的距离和条形高度 const barStep = yScale.step(); const barHeight = yScale.bandwidth(); // 计算标签和图标可用的空间(条形上方的空间) const availableLabelSpace = barStep - barHeight; // 设置标签和图标的最大高度,确保不会重叠 // 允许标签和图标总高度最多占可用空间的90% const maxTotalHeight = availableLabelSpace * 0.9; // 为标签和图标分配空间 // 图标大小设为总高度的65%,文本设为35% const iconHeight = Math.min(barHeight * 0.8, maxTotalHeight * 0.65); const iconWidth = iconHeight; // 保持图标宽高比 // 基于图标的高度计算合适的字体大小,因为它们是并排的 // 字体大小通常是所需高度的约80% const targetFontSizeBasedOnIcon = iconHeight * 0.9; const fontSize = Math.max(4, Math.min(16, targetFontSizeBasedOnIcon)); // 限制字体大小在8px到12px之间 // ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 为每个维度创建独立的渐变 ---------- sortedDimensions.forEach((dimension, i) => { // 获取条形颜色 - 从colors.field中获取,如果不存在则使用默认主色 let barColor = colorResolver.other("primary").value; barColor = colorResolver.field(dimension, 0, { fallback: barColor }).value; // 为每个条形创建专用渐变 const gradient = defs.append("linearGradient") .attr("id", `bar-gradient-${i}`) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(barColor, { mode: "darker", amount: 0.3 })); // 左侧暗色 gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(barColor, { mode: "brighter", amount: 0.8 })); // 右侧亮色 }); // ---------- 11. 绘制条形和标签 ---------- // 为每个维度绘制条形和标签 sortedDimensions.forEach((dimension, i) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barWidth = getBarWidth(+dataPoint[valueField]); const yPosition = yScale(dimension); // ---------- 创建条形组 ---------- const barGroup = g.append("g") .attr("transform", `translate(0, ${yPosition})`); // ---------- 添加图标和维度标签(在条形上方)---------- // 创建一个用于图标和标签的容器组 const labelGroup = g.append("g") .attr("transform", `translate(0, ${yPosition - 2})`); // 紧贴条形上方的位置 // 标签水平位置 - 根据是否有图标调整 let labelX = 0; // 默认从左侧开始 // 添加图标(如果有) if (images.field && images.field[dimension]) { labelGroup.append("image") .attr("x", 0) // 与条形左侧对齐 .attr("y", -iconHeight) // 图标放在条形上方 .attr("width", iconWidth) .attr("height", iconHeight) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xlink:href", images.field[dimension]); // 如果有图标,调整标签位置 labelX = iconWidth + 5; } // 添加维度标签 labelGroup.append("text") .attr("x", labelX) .attr("y", -iconHeight / 2) // 垂直位置与图标中心对齐 .attr("dy", "0.35em") // 垂直微调以居中 .attr("text-anchor", "start") // 左对齐 .style("font-family", typography.label.font_family) .style("font-size", `${fontSize}px`) // 使用新的fontSize .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension); // ---------- 绘制条形 ---------- // 获取条形颜色 let barColor = colorResolver.other("primary").value; barColor = colorResolver.field(dimension, 0, { fallback: barColor }).value; // 绘制条形 - 右侧带有圆角 barGroup.append("path") .attr("d", function() { const radius = barHeight / 2; // 处理零或负值,避免绘制错误 if (barWidth <= 0) { return ""; // 不绘制任何路径 } // 当条形宽度小于半径时,绘制一个椭圆弧段,确保最右点为 barWidth if (barWidth < radius) { // M 移动到起点 (0, 0) // A 绘制椭圆弧: rx=barWidth, ry=radius, 旋转=0, 小弧=0, 顺时针=1, 终点=(0, barHeight) // Z 关闭路径 return `M 0,0 A ${barWidth},${radius} 0 0,1 0,${barHeight} Z`; } // 当条形宽度大于等于半径时,绘制矩形 + 半圆 else { // M 移动到起点 (0, 0) // H 水平线到半圆开始处 (barWidth - radius, 0) // A 绘制标准圆弧: rx=radius, ry=radius, 旋转=0, 小弧=0, 顺时针=1, 终点=(barWidth - radius, barHeight) // H 水平线回到左侧 (0, barHeight) // Z 关闭路径 return `M 0,0 H ${barWidth - radius} A ${radius},${radius} 0 0,1 ${barWidth - radius},${barHeight} H 0 Z`; } }) .attr("fill", `url(#bar-gradient-${i})`) // 使用每个条的独立渐变 .style("stroke", "none"); // 添加数值标签(在条形右侧) const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; barGroup.append("text") .attr("x", barWidth + 5) // 条形右侧5px .attr("y", barHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326/* REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_19", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 右对齐水平条形图实现 - 使用D3.js (集成图标和独立颜色) horizontal_bar_chart_11function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333", other: { primary: "#E74C3C" } // 默认使用红色作为条形颜色 }; const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 const images = jsonData.images || {}; // 获取图标数据 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 - 增加顶部边距以容纳Y轴名称和第一个标签/图标 const margin = { top: 100, // 增加顶部边距 right: 10, // 最小右侧边距 bottom: 60, // 底部边距 left: 10 // 左侧边距,留足空间放置数值标签 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ---------- // 获取唯一维度值 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 按数值从小到大排序数据 const orderedData = [...chartData].sort((a, b) => +a[valueField] - +b[valueField]); const orderedDimensions = orderedData.map(d => d[dimensionField]); // 计算最小和最大值用于比例尺 const minValue = d3.min(chartData, d => +d[valueField]); const maxValue = d3.max(chartData, d => +d[valueField]); // 确定是否有负值 const hasNegativeValues = minValue < 0; // 添加数值格式化函数 // ---------- 5. 计算标签宽度和图表尺寸 ---------- // 创建临时SVG来测量文本宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden"); // 计算最大维度标签宽度(用于潜在的布局调整,这里暂时不用) let maxLabelWidth = 0; dimensions.forEach(dimension => { const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; const textWidth = chartUtils.text.measure(tempSvg, formattedDimension, { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }).width; maxLabelWidth = Math.max(maxLabelWidth, textWidth); }); // 计算最大数值标签宽度 let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`; const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width; maxValueWidth = Math.max(maxValueWidth, textWidth); }); // 删除临时SVG tempSvg.remove(); // 根据数值标签宽度调整左边距 margin.left = Math.max(margin.left, maxValueWidth + 10); // 增加一点间距 // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // ---------- 7. 创建比例尺 ---------- // 计算条形的额外间距(如果启用) const barPadding = 0.55; // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(orderedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(用于数值)- 右对齐 const xScale = d3.scaleLinear() .domain([ hasNegativeValues ? Math.min(minValue * 1.1, 0) : 0, Math.max(maxValue * 1.1, 0) ]) .range([0, innerWidth]); // ---------- 8. 动态图标和标签大小计算 (恢复基于可用空间) ---------- const barStep = yScale.step(); const barHeight = yScale.bandwidth(); // 计算条形本身之间的垂直间隙 const gapBetweenBars = barStep - barHeight; // 允许图标/标签使用的最大垂直空间(例如,间隙的80%) const maxTotalHeight = Math.max(15, gapBetweenBars * 0.8); // 保证最小15px
// 根据最大总高度分配图标和标签的高度 // 图标高度占总高度的约 70%,但不超过 barHeight 的 90%,且不超过20px const iconHeight = Math.min(barHeight * 0.9, maxTotalHeight * 0.7, 20); const iconWidth = iconHeight; // 保持图标宽高比
// 基于图标高度计算维度标签的字体大小 (因为并排) const targetLabelFontSize = iconHeight * 0.9; const labelFontSize = `${Math.max(4, Math.min(16, targetLabelFontSize))}px`; // 限制范围 8px-16px, 并转为字符串
// ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 添加Y轴名称 (Value Field Name) ---------- const yAxisName = valueField; // Y轴使用的字段名 g.append("text") .attr("x", innerWidth) // 右对齐到绘图区边缘 .attr("y", -5) .attr("dy", "0.35em") // 垂直微调 .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) // 使用label的字体设置 .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) // 默认文本颜色 .text(yAxisName); // ---------- 11. 绘制条形、标签和图标 ---------- orderedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const yPosition = yScale(dimension); const value = +dataPoint[valueField]; // 获取特定颜色和图标 const barColor = colorResolver.field(dimension, 0, { fallbackKey: "primary" }).value; const iconSrc = (images.field && images.field[dimension]) ? images.field[dimension] : null;
// 为每个bar创建独立的渐变 const gradientId = `bar-gradient-${index}`; const gradient = defs.append("linearGradient") .attr("id", gradientId) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%");
// 定义从左到右的渐变,中间最亮,两边较暗 gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(barColor, { mode: "darker", amount: 0.3 }));
gradient.append("stop") .attr("offset", "50%") .attr("stop-color", colorResolver.variant(barColor, { mode: "brighter", amount: 2.5 }));
gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(barColor, { mode: "darker", amount: 0.3 }));
// 计算条形宽度和位置 - 右对齐 let barWidth = Math.abs(xScale(value) - xScale(0)); let barX = value >= 0 ? innerWidth - barWidth : innerWidth - barWidth; // 考虑负值(虽然此图表类型通常不处理) // ---------- 添加图标和维度标签(条形上方,右对齐 - 使用动态计算)---------- let labelEndX = innerWidth; // 标签默认结束于右边缘
// 添加图标(如果存在) if (iconSrc) { g.append("image") // 直接添加到主绘图组g .attr("x", innerWidth - iconWidth) // 使用动态iconWidth .attr("y", yPosition - iconHeight - 5) // 使用动态iconHeight .attr("width", iconWidth) .attr("height", iconHeight) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xlink:href", iconSrc); // 如果有图标,标签向左移动一点 labelEndX = innerWidth - iconWidth - 8; // 8px间距 } // 添加维度标签 const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; g.append("text") // 直接添加到主绘图组g .attr("x", labelEndX) // 结束位置(右对齐) // 垂直居中于图标的位置 (基于动态 iconHeight) .attr("y", yPosition - 5 - iconHeight / 2) .attr("dy", "0.35em") // 垂直微调 .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", labelFontSize) // 使用动态计算的字号 .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedDimension);
// ---------- 创建条形组(为了方便管理标签和条形) ---------- const barGroup = g.append("g") .attr("transform", `translate(0, ${yPosition})`); // ---------- 绘制条形 (简化实现,使用rect元素实现左侧圆角) ---------- barGroup.append("rect") .attr("x", barX) .attr("y", 0) .attr("width", barWidth) .attr("height", barHeight) .attr("fill", `url(#${gradientId})`) // 使用每个bar独立的渐变 .attr("rx", barHeight / 4) // 左侧圆角 .attr("ry", barHeight / 4); // ---------- 添加数值标签(条形外侧左边) ---------- const formattedValue = valueUnit ? `${chartUtils.format.autoText(value)}${valueUnit}` : `${chartUtils.format.autoText(value)}`; barGroup.append("text") .attr("x", barX - 5) // 条形外左侧5px .attr("y", barHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "end") // 右对齐(相对于x坐标) .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(18, Math.max(barHeight * 0.5, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) // 使用默认文本颜色 .text(formattedValue); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_2", "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[3, 20], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary", "secondary", "background"], "supported_effects": ["gradient", "opacity"], "min_height": 600, "min_width": 800, "background": "light", "icon_mark": "none", "icon_label": "none", "has_x_axis": "yes", "has_y_axis": "yes"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data; // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置,如果不存在则使用默认值 title: { font_family: "Arial", font_size: "18px", font_weight: "bold" }, label: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, description: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } }; const colors = jsonData.colors || { text_color: "#333333", other: { primary: "#D32F2F", // Red for "Still active" secondary: "#AAAAAA", // Gray for "Ended" background: "#F0F0F0" } }; // 颜色设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 数值单位规范 // 添加数值格式化函数 // 设置视觉效果变量的默认值 variables.has_shadow = variables.has_shadow || false; variables.has_stroke = variables.has_stroke || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 600; const height = variables.height || 400; // 设置边距 const margin = { top: 50, right: 30, bottom: 80, left: 40 }; // 计算实际绘图区域大小 const chartWidth = width - margin.left - margin.right; const chartHeight = height - margin.top - margin.bottom; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列获取字段名 const xField = chartUtils.schema.channel(jsonData, "x").key || "period"; const yField = chartUtils.schema.channel(jsonData, "y").key || "value"; // 获取字段单位(如果存在) let xUnit = ""; let yUnit = ""; let groupUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { xUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { yUnit = chartUtils.schema.channel(jsonData, "y").unit; }
// ---------- 4. 数据处理 ---------- // 处理数据,确保数据格式正确 const processedData = chartData.map(d => ({ category: d[xField], value: +d[yField] // 确保转换为数字 })); // ---------- 5. 创建比例尺 ---------- // Y轴比例尺 - 使用分类数据 const yScale = d3.scaleBand() .domain(processedData.map(d => d.category)) .range([0, chartHeight]) .padding(0.3); // X轴比例尺 - 使用数值 const xScale = d3.scaleLinear() .domain([0, d3.max(processedData, d => d.value)]) .range([0, chartWidth]) .nice();
const n_data = processedData.length // 颜色比例尺 const colorScale = (d, i) => { if (i === n_data - 1) { return colorResolver.variant(colorResolver.other("primary").value, { mode: "brighter", amount: 0.8 }); } return colorResolver.other("primary").value; };
// 确定标签的最大长度: let minYLabelRatio = 1.0 const maxYLabelWidth = yScale.bandwidth() * 1.03
chartData.forEach(d => { const yLabelText = String(d[xField]) let currentWidth = chartUtils.text.measure(null, yLabelText).width if (currentWidth > maxYLabelWidth) { minYLabelRatio = Math.min(minYLabelRatio, maxYLabelWidth / currentWidth) } })
// ---------- 6. 创建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"); // 添加图表主体容器 const chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 7. 绘制图表元素 ---------- // 添加X轴 const xAxis = d3.axisBottom(xScale) .ticks(5) .tickFormat(d => chartUtils.format.autoText(d) + (yUnit ? ` ${yUnit}` : '')) .tickSize(0) // 移除刻度线 .tickPadding(10); // 增加文字和轴的间距 chartGroup.append("g") .attr("class", "x-axis") .attr("transform", `translate(0, ${chartHeight})`) .call(xAxis) .call(g => g.select(".domain").remove()) // 移除轴线 .selectAll("text") .remove(); // 添加Y轴 const yAxis = d3.axisLeft(yScale) .tickSize(0); // 移除刻度线 chartGroup.append("g") .attr("class", "y-axis") .call(yAxis) .selectAll("text") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("text-anchor", "end") .attr("dy", "0.32em") .attr("x", -10) .style("fill", colorResolver.text({ fallback: "#333333" }).value); // 添加条形 const bars = chartGroup.selectAll(".bar") .data(processedData) .enter() .append("rect") .attr("class", "bar") .attr("y", d => yScale(d.category)) .attr("x", 0) .attr("width", d => xScale(d.value)) .attr("height", yScale.bandwidth()) .attr("fill", (d, i) => colorScale(d, i)); // 添加数值标签 const labels = chartGroup.selectAll(".label") .data(processedData) .enter() .append("text") .attr("class", "label") .attr("x", d => xScale(d.value) + 5) .attr("y", d => yScale(d.category) + yScale.bandwidth() / 2) .attr("dy", "0.32em") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(d => chartUtils.format.autoText(d.value) + (yUnit ? ` ${yUnit}` : '')) .style("opacity", 1); // 直接设置为可见
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_20", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["x"], "supported_effects": ["radius_corner", "gradient", "stroke"], "min_height": 400, "min_width": 400, "background": "none", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.js horizontal_bar_chart_composite_02function makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ----------
// 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义
// 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_stroke = variables.has_stroke || false;
// 清空容器 d3.select(containerSelector).html("");
// ---------- 2. 尺寸和布局设置 ----------
// 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600;
// 设置边距 - 初始值,稍后会根据标签长度调整 const margin = { top: 90, // 顶部留出标题空间 right: 40, // 右侧足够显示数值 bottom: 40, // 底部边距 left: 40 // 左侧空间,稍后会调整 };
// ---------- 3. 提取字段名和单位 ----------
// 根据数据列提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "dimension"; const valueField = chartUtils.schema.channel(jsonData, "y").key || "value"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "total";
// 获取字段单位 let valueUnit = ""; let valueUnit2 = ""; valueUnit = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y2").unit; // 添加维度单位定义 const dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "x").unit;
// 获取y2字段的显示名称用于标题 const valueField2Name = chartUtils.schema.channel(jsonData, "y2").raw?.display_name || valueField2;
// ---------- 4. 数据处理 ----------
// 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))];
// 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]);
// 添加数值格式化函数
// ---------- 5. 计算标签宽度 ----------
// 序号宽度 const rankingWidth = 25;
// 图标尺寸 let flagWidth = 40; let flagHeight = 40; const flagPadding = 5; // 图标与标签之间的间距 const labelMeasureOptions = { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }; const annotationMeasureOptions = { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight };
// 计算最大维度标签宽度(不包括图标和序号) let maxLabelWidth = 0; dimensions.forEach(dimension => { // 格式化维度名称(附加单位,如果有) const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`;
const textWidth = chartUtils.text.measure(null, formattedDimension, labelMeasureOptions).width; maxLabelWidth = Math.max(maxLabelWidth, textWidth); });
// 计算最大数值标签宽度 let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`;
const textWidth = chartUtils.text.measure(null, formattedValue, annotationMeasureOptions).width;
maxValueWidth = Math.max(maxValueWidth, textWidth); });
// 计算最大第二数值标签宽度 let maxValueWidth2 = 0; chartData.forEach(d => { const formattedValue2 = valueUnit2 ? `${chartUtils.format.autoText(+d[valueField2])}${valueUnit2}` : `${chartUtils.format.autoText(+d[valueField2])}`;
const textWidth = chartUtils.text.measure(null, formattedValue2, annotationMeasureOptions).width;
maxValueWidth2 = Math.max(maxValueWidth2, textWidth); });
// 计算y2字段标题的宽度 const y2TitleWidth = chartUtils.text.measure(null, valueField2Name, labelMeasureOptions).width;
// 使用最大的第二值宽度和标题宽度 maxValueWidth2 = Math.max(maxValueWidth2, y2TitleWidth);
// 计算左边距,考虑 标签 + 图标之间的间距 // 序号在最左边,然后是标签(右对齐),然后是图标 const totalLeftPadding = maxLabelWidth + flagWidth + flagPadding; margin.left = Math.max(margin.left, totalLeftPadding);
// 设置右边距,考虑第二个数值标签 + 固定距离 20px margin.right = Math.max(margin.right, maxValueWidth2 + 10);
// 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;
// ---------- 6. 创建SVG容器 ----------
const svg = d3.select(containerSelector) .append("svg") .attr("width", width) // 使用固定宽度而不是百分比 .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"); // 如果有背景颜色设置,添加背景 if (colorResolver.background({ fallback: "#FFFFFF" }).value) { svg.style("background-color","#8BC34A" ); } // 添加defs用于视觉效果 const defs = svg.append("defs");
// 获取主题色 const primaryColor = colorResolver.other("primary", { fallback: "#1d6b64" }).value;
// 添加水平渐变(从左到右) const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%");
gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.3 }));
gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 }));
// ---------- 7. 创建比例尺 ----------
// 设置固定的条形间距 const barPadding = 0.2;
// Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
// X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添加5%边距 .range([0, innerWidth]);
// ---------- 9. 创建主图表组 ----------
const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`);
// ---------- 10. 绘制条形和标签 ----------
// 获取描边颜色的辅助函数 const getStrokeColor = (dimension) => { // 获取条形的基础颜色 const baseColor = getBarColor(dimension); // 返回该颜色的更亮版本 return colorResolver.variant(baseColor, { mode: "brighter", amount: 3 }); };
// 获取条形颜色的辅助函数 const getBarColor = (dimension) => { // 获取维度对应的颜色 return colorResolver.field(dimension, 0, { fallback: primaryColor }).value; };
// 计算图标区域的尺寸和位置 const barHeight = yScale.bandwidth(); const iconWidth = barHeight * 1.1; // 与下方图标尺寸保持一致 const iconX = -iconWidth - flagPadding; const iconContainerWidth = iconWidth + 2*flagPadding; // 图标宽度加上一些额外的空间,用于覆盖条形图的一部分 const iconContainerHeight = innerHeight;
// 添加y2字段标题(在第一行上方) g.append("text") .attr("x", innerWidth + margin.right - 10) // 右对齐,距离图表右边缘10px .attr("y", - 5) .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(valueField2Name);
// 为每个维度绘制条形和标签 sortedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension);
if (dataPoint) { const barHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]);
// 绘制条形 g.append("rect") .attr("x", 0) .attr("y", yScale(dimension)) .attr("width", barWidth) .attr("height", barHeight) .attr("fill", "url(#bar-gradient)") // 强制使用渐变填充 .attr("rx", 4) // 强制使用圆角半径4 .attr("ry", 4) // 强制使用圆角半径4 .style("stroke", getStrokeColor(dimension)) // 强制应用描边 .style("stroke-width", 1) // 强制设置描边宽度为1 .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); });
// 设置图标尺寸与条形高度一致 const adjustedFlagWidth = barHeight*1.1; // 图标宽度与条形高度相同 const adjustedFlagHeight = barHeight*1.1; // 图标高度与条形高度相同
// 计算每个标签的位置 // 图标位置:紧贴条形左边 const iconX = -adjustedFlagWidth - flagPadding;
const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`;
// 标签位置:在图标左侧,右对齐(相对于最长标签) const labelX = iconX - flagPadding;
// 添加维度图标 if (images.field && images.field[dimension]) { // 设置图标尺寸为条形高度的90% const iconHeight = barHeight * 0.9; const iconWidth = iconHeight; // 保持正方形 const centerY = yScale(dimension) + barHeight / 2; const clipPathId = `clip-${dimension.replace(/\W/g, '')}-${index}`;
// 创建裁剪路径 defs.append("clipPath") .attr("id", clipPathId) .append("circle") .attr("cx", iconX + iconWidth/2) .attr("cy", centerY) .attr("r", iconWidth * 0.5);
// 绘制细边框圆圈 g.append("circle") .attr("cx", iconX + iconWidth/2) .attr("cy", centerY) .attr("r", iconWidth * 0.5) .attr("fill", "none") .attr("stroke", "#000") .attr("stroke-width", 0.5);
// 添加裁剪后的图像 g.append("image") .attr("x", iconX) .attr("y", centerY - iconHeight/2) .attr("width", iconWidth) .attr("height", iconHeight) .attr("clip-path", `url(#${clipPathId})`) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xlink:href", images.field[dimension]); }
// 添加维度标签 g.append("text") .attr("x", labelX) .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", `${Math.max(barHeight * 0.5, 8)}px`) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedDimension);
// 计算动态字体大小(条形高度的60%) const dynamicFontSize = `${Math.max(barHeight * 0.5, 8)}px`; // 格式化数值 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`;
const valueTextWidth = chartUtils.text.measure(g, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: dynamicFontSize, fontWeight: typography.annotation.font_weight }).width;
// 判断是否能在条形内部放置文本(需要多留一些边距) const textFitsInside = barWidth > valueTextWidth + 5;
// 添加数值标签(在条形内部或外部) g.append("text") .attr("x", textFitsInside ? barWidth / 2 : barWidth + 5) // 内部居中,外部在右侧 .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("text-anchor", textFitsInside ? "middle" : "start") // 内部居中对齐,外部左对齐 .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", textFitsInside ? "#ffffff" : colorResolver.text({ fallback: "#333333" }).value) // 在内部时使用白色,在外部时使用文本颜色 .text(formattedValue);
// 格式化第二数值 const formattedValue2 = valueUnit2 ? `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}` : `${chartUtils.format.autoText(+dataPoint[valueField2])}`;
// 添加第二数值标签(在右边缘,右对齐,距离右边缘20px) g.append("text") .attr("x", innerWidth + margin.right - 20) // 右对齐,距离图表右边缘20px .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue2); } });
// 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_21", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 20], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary","secondary"], "supported_effects": ["radius_corner", "gradient", "stroke"], "min_height": 400, "min_width": 400, "background": "none", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.js horizontal_bar_chart_composite_03function makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ----------
// 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义
// 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_stroke = variables.has_stroke || false;
// 清空容器 d3.select(containerSelector).html("");
// ---------- 2. 尺寸和布局设置 ----------
// 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600;
// 设置边距 - 初始值,稍后会根据标签长度调整 const margin = { top: 90, // 顶部留出标题空间 right: 40, // 右侧足够显示数值 bottom: 40, // 底部边距 left: 40 // 左侧空间,稍后会调整 };
// ---------- 3. 提取字段名和单位 ----------
// 根据数据列提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "dimension"; const valueField = chartUtils.schema.channel(jsonData, "y").key || "value"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "total";
// 获取字段单位 let valueUnit = ""; let valueUnit2 = ""; valueUnit = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y2").unit; // 添加维度单位定义 const dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "x").unit;
// 获取y2字段的显示名称用于标题 const valueField2Name = chartUtils.schema.channel(jsonData, "y2").raw?.display_name || valueField2; // 获取y1字段的显示名称用于标题 const valueFieldName = chartUtils.schema.channel(jsonData, "y").raw?.display_name || valueField;
// ---------- 4. 数据处理 ----------
// 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))];
// 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]);
// 添加数值格式化函数
// 计算图标尺寸 const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
// 智能换行:优先按单词;利用率不足50%时尝试塞字母;长词断行加"-";断词后下一行单字母开头尽量回并 const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; };
// ---------- 5. 计算标签宽度 ----------
// 图标尺寸 const flagPadding = 5; // 图标与标签之间的间距
// 使用智能换行计算标签布局 const estimatedBarHeight = (height - margin.top - margin.bottom) / sortedDimensions.length / (1 + 0.2); const targetFontSize = Math.max(estimatedBarHeight * 0.4, 8); const maxLabelWidthAvailable = 200; // 标签最大可用宽度 const labelLineSpacing = 1.2;
const labelLayout = buildDimLabelLayout({ containerSelector: containerSelector, labels: sortedDimensions, fontConfig: { font_family: typography.label.font_family, font_weight: typography.label.font_weight }, maxWidth: maxLabelWidthAvailable, maxHeight: estimatedBarHeight, lineSpacing: labelLineSpacing, targetFontSize: targetFontSize });
const dimLabelConfig = labelLayout.dimLabelConfig; const maxLabelWidth = labelLayout.maxLabelWidth;
// 计算最大数值标签宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`;
const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width;
maxValueWidth = Math.max(maxValueWidth, textWidth); });
// 计算最大第二数值标签宽度 let maxValueWidth2 = 0; chartData.forEach(d => { const formattedValue2 = valueUnit2 ? `${chartUtils.format.autoText(+d[valueField2])}${valueUnit2}` : `${chartUtils.format.autoText(+d[valueField2])}`;
const textWidth = chartUtils.text.measure(tempSvg, formattedValue2, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width;
maxValueWidth2 = Math.max(maxValueWidth2, textWidth); });
// 计算y2字段标题的宽度 const y2TitleWidth = chartUtils.text.measure(tempSvg, valueField2Name, { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }).width;
// 使用最大的第二值宽度和标题宽度 maxValueWidth2 = Math.max(maxValueWidth2, y2TitleWidth);
// 删除临时SVG tempSvg.remove();
// 计算左边距,仅考虑标签宽度和一些间距 margin.left = Math.max(margin.left, maxLabelWidth + flagPadding * 2);
// 设置右边距,考虑第二个数值标签 + 固定距离 20px margin.right = Math.max(margin.right, maxValueWidth2 + 10);
// 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;
// ---------- 6. 创建SVG容器 ----------
const svg = d3.select(containerSelector) .append("svg") .attr("width", width) // 使用固定宽度而不是百分比 .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"); // 如果有背景颜色设置,添加背景 if (colorResolver.background({ fallback: "#FFFFFF" }).value) { svg.style("background-color","#8BC34A" ); } // 添加defs用于视觉效果 const defs = svg.append("defs");
// 获取主题色 const primaryColor = colorResolver.other("primary", { fallback: "#1d6b64" }).value; const secondaryColor = colorResolver.other("secondary", { fallback: "#ff7f0e" }).value; // 获取次要颜色,设置默认值
// ---------- 7. 创建比例尺 ----------
// 设置固定的条形间距 const barPadding = 0.2;
// Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
// X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添加5%边距 .range([0, innerWidth]);
// 为右侧正方形创建面积比例尺 const barH = yScale.bandwidth(); // 获取单个bar的高度 const maxY2 = d3.max(chartData, d => +d[valueField2]); const minSideLength = 10; // 最小边长 const maxSideLength = barH * 2; // 最大边长 const squareSideScale = d3.scaleSqrt() // 使用sqrt比例尺映射面积到边长 .domain([0, maxY2]) // Y2值范围 .range([minSideLength, maxSideLength]) // 映射到边长范围 .clamp(true); // 防止超出范围
// ---------- 9. 创建主图表组 ----------
const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`);
// ---------- 10. 绘制条形和标签 ----------
// 获取条形颜色的辅助函数 const getBarColor = (dimension) => { // 获取维度对应的颜色 return colorResolver.field(dimension, 0, { fallback: primaryColor }).value; };
// 计算图标区域的尺寸和位置 const barHeight = yScale.bandwidth(); const iconWidth = barHeight * 1.1; // 与下方图标尺寸保持一致 const iconX = -iconWidth - flagPadding; const iconContainerWidth = iconWidth + 2*flagPadding; // 图标宽度加上一些额外的空间,用于覆盖条形图的一部分 const iconContainerHeight = innerHeight;
// 添加y1字段标题(在第一行上方,左对齐) g.append("text") .attr("x", 0) // 左对齐到条形图起点 .attr("y", -10) // 与y2标题垂直对齐 .attr("text-anchor", "start") // 左对齐 .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(valueFieldName);
// 添加y2字段标题(在第一行上方) g.append("text") .attr("x", innerWidth + margin.right - 10) // 右对齐,距离图表右边缘10px .attr("y", - 10) .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(valueField2Name);
// 为每个维度绘制条形和标签 sortedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension);
if (dataPoint) { const barHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]);
// 绘制条形 g.append("rect") .attr("x", 0) .attr("y", yScale(dimension)) .attr("width", barWidth) .attr("height", barHeight) .attr("fill", primaryColor) // 强制使用主颜色填充 .attr("rx", barHeight / 2) // 强制使用圆角半径 barHeight / 2 .attr("ry", barHeight / 2) // 强制使用圆角半径 barHeight / 2 .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); });
// 标签位置:条形左侧,右对齐 const labelX = -flagPadding; const centerY = yScale(dimension) + barHeight / 2;
// 添加维度标签(支持智能换行) const labelConfig = dimLabelConfig[dimension]; const labelGroup = g.append("text") .attr("x", labelX) .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
if (labelConfig.needsWrapping) { // 多行换行 const lineHeight = labelConfig.lineHeight; const startY = centerY - ((labelConfig.lines.length - 1) * lineHeight) / 2; labelGroup.attr("y", startY);
labelConfig.lines.forEach((line, i) => { labelGroup.append("tspan") .attr("x", labelX) .attr("dy", i === 0 ? "0.35em" : `${lineHeight}`) .text(line); }); } else { // 单行 labelGroup .attr("y", centerY) .attr("dy", "0.35em") .text(labelConfig.lines[0]); }
// 计算动态字体大小(条形高度的60%) const dynamicFontSize = `${Math.max(barHeight * 0.4, 8)}px`; // 格式化数值 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`;
const valueTextWidth = chartUtils.text.measure(svg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: dynamicFontSize, fontWeight: typography.annotation.font_weight }).width;
// -- 计算 Y2 和正方形属性 -- (移到此处) const y2Value = +dataPoint[valueField2]; const sideLength = squareSideScale(y2Value); const squareX = innerWidth + margin.right / 2 - sideLength / 2; // 水平居中于右侧边距 const squareY = yScale(dimension) + barHeight / 2 - sideLength / 2; // 垂直居中于条形 const formattedValue2 = valueUnit2 ? `${chartUtils.format.autoText(y2Value)}${valueUnit2}` : `${chartUtils.format.autoText(y2Value)}`;
// -- 添加 Y 数值标签 (考虑重叠) -- const textFitsInside = barWidth > valueTextWidth + 10; // 内部判断加宽边距 const outsideX = barWidth + 5; const wouldOverlap = !textFitsInside && (outsideX + valueTextWidth > squareX);
let labelXPos, labelAnchor, labelFill; if (textFitsInside) { labelXPos = barWidth / 2; labelAnchor = "middle"; labelFill = "#ffffff"; } else if (wouldOverlap) { labelXPos = barWidth / 2; // 强制放内部 labelAnchor = "middle"; labelFill = "#ffffff"; // 内部用白色 } else { labelXPos = outsideX; // 放外部 labelAnchor = "start"; labelFill = colorResolver.text({ fallback: "#333333" }).value; }
g.append("text") .attr("x", labelXPos) .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("text-anchor", labelAnchor) .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", labelFill) .text(formattedValue);
// -- 绘制右侧正方形 -- g.append("rect") .attr("x", squareX) .attr("y", squareY) .attr("width", sideLength) .attr("height", sideLength) .attr("fill", secondaryColor) .attr("opacity", 0.6);
// -- 添加 Y2 数值标签 (居中于正方形) -- g.append("text") .attr("x", squareX + sideLength / 2) // 水平居中 .attr("y", squareY + sideLength / 2) // 垂直居中 .attr("dy", "0.35em") .attr("text-anchor", "middle") // 居中对齐 .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) // Use same dynamic font size .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue2);
} });
// 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_22", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": ["primary"], "supported_effects": [], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图与比例方形复合图表实现 - 使用D3.jshorizontal_bar_chart_composite_04function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ----------
// 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置,如果不存在则使用默认值 title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { text_color: "#000000", background_color: "#FFFFFF", other: { primary: "#83C341" } }; const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 const titles = jsonData.titles || {}; // 标题配置
// 清空容器 d3.select(containerSelector).html("");
// ---------- 2. 尺寸和布局设置 ----------
// 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600;
// 设置边距 const margin = { top: 100, // 顶部留出标题空间 right: 5, // 右侧边距 bottom: 40, // 底部边距 left: 10 // 左侧边距,给文字留出一些空间 };
// ---------- 3. 提取字段名和单位 ----------
// 根据数据列提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y", { fallbackKey: "Crypto Ownership Percentage" }).key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners";
// 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : "";
// 列标题(使用数据列的name字段,而不是description) const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners";
// ---------- 4. 数据处理 ----------
// 按第一个数值字段降序排序数据 const sortedData = [...chartData].sort((a, b) => b[valueField1] - a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]);
// 添加数值格式化函数
// ---------- 5. 布局计算 ---------- const flagWidth = 30; // 图标宽度 const flagHeight = 30; // 图标高度 const textPadding = 5; // 文本与图标/边缘的间距 const labelGap = 10; // 外部标签间距
// 更新左边距 (仅考虑图标和padding) const requiredLeftSpace = flagWidth + textPadding; margin.left = requiredLeftSpace + 5; // 加5px额外缓冲
// 设置条形图和方形图的布局比例 const leftColumnRatio = 0.85; // 左列占比 const rightColumnRatio = 0.15; // 右列占比
// 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;
// 计算两列的宽度 const barChartWidth = innerWidth * leftColumnRatio; const circleChartWidth = innerWidth * rightColumnRatio;
// ---------- 6. 创建比例尺 ----------
// 计算条形的额外间距(如果启用) const barPadding = 0.2;
// Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
// X轴比例尺(用于第一个数值)- 条形图 const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, barChartWidth]);
// 正方形面积比例尺(用于第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); const minSideLength = yScale.bandwidth() * 0.1; // 最小边长为bar height的10% const maxSideLength = Math.min(yScale.bandwidth() * 1.0, circleChartWidth * 0.8); // 最大边长
const squareSideScale = d3.scaleSqrt() // 使用平方根比例尺确保面积比例正确 .domain([0, maxValue2]) .range([minSideLength, maxSideLength]);
// ---------- 7. 创建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");
// ---------- 8. 添加SVG定义 ----------
// ---------- 9. 添加标题和标题下的线条 ----------
// 计算标题位置 const titleY = margin.top - 25; const lineY = margin.top - 10;
// 创建一个临时的SVG元素用于文本测量 const tempTextSvg = d3.select(containerSelector).append("svg") .attr("width", 0) .attr("height", 0) .style("opacity", 0) .style("position", "absolute");
// ---------- Helper: Get Wrapped Lines ---------- function getWrappedLines(textContent, availableWidth, fontConfig, tempSvg) { const words = (textContent || "").trim().toUpperCase().split(/\s+/).filter(w => w !== ""); // 转大写 const lines = []; const fontSizeValue = parseFloat(fontConfig.font_size); const lineHeight = fontSizeValue * 1.2;
if (words.length === 0) { return { linesArray: [], numLines: 0, lineHeight: lineHeight }; }
let currentLine = words[0]; for (let i = 1; i < words.length; i++) { const word = words[i]; const testLine = currentLine + " " + word; if (estimateGenericTextWidth(testLine, fontConfig, tempSvg) > availableWidth && currentLine !== "") { lines.push(currentLine); currentLine = word; } else { currentLine = testLine; } } if (currentLine !== "") { lines.push(currentLine); }
return { linesArray: lines, numLines: lines.length, lineHeight: lineHeight }; }
// ---------- Helper: Estimate Generic Text Width ---------- function estimateGenericTextWidth(text, fontConfig, tempSvg) { return chartUtils.text.measure(tempSvg, text, { fontFamily: fontConfig.font_family, fontSize: fontConfig.font_size, fontWeight: fontConfig.font_weight }).width; };
// ---------- 重构标题部分 ---------- const titleFontConfig = typography.description; const titleBottomPadding = 10; // 标题底部与横线之间的间距 const desiredBaselineOfLastLine = lineY - titleBottomPadding; // 横线上方10px
// 左侧列标题 const leftTitleAvailableWidth = barChartWidth * 0.9; // 左侧标题可用宽度,给一些padding const leftTitleXPos = margin.left; const wrappedLeftTitle = getWrappedLines(columnTitle1, leftTitleAvailableWidth, titleFontConfig, tempTextSvg);
if (wrappedLeftTitle.numLines > 0) { const initialYLeft = desiredBaselineOfLastLine - (wrappedLeftTitle.numLines - 1) * wrappedLeftTitle.lineHeight; const leftTitleText = svg.append("text") .attr("x", leftTitleXPos) .attr("y", initialYLeft) .attr("text-anchor", "start") .style("font-family", titleFontConfig.font_family) .style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
wrappedLeftTitle.linesArray.forEach((line, i) => { leftTitleText.append("tspan") .attr("x", leftTitleXPos) .attr("dy", i === 0 ? 0 : wrappedLeftTitle.lineHeight) .text(line); }); }
// 右侧列标题 const rightTitleAvailableWidth = circleChartWidth * 0.9; // 右侧标题可用宽度 const rightTitleXPos = margin.left + barChartWidth + circleChartWidth; // 右对齐到右侧区域的末尾 const wrappedRightTitle = getWrappedLines(columnTitle2, rightTitleAvailableWidth, titleFontConfig, tempTextSvg);
if (wrappedRightTitle.numLines > 0) { const initialYRight = desiredBaselineOfLastLine - (wrappedRightTitle.numLines - 1) * wrappedRightTitle.lineHeight; const rightTitleText = svg.append("text") .attr("x", rightTitleXPos) .attr("y", initialYRight) .attr("text-anchor", "end") // 右侧标题右对齐 .style("font-family", titleFontConfig.font_family) .style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
wrappedRightTitle.linesArray.forEach((line, i) => { rightTitleText.append("tspan") .attr("x", rightTitleXPos) .attr("dy", i === 0 ? 0 : wrappedRightTitle.lineHeight) .text(line); }); }
// 标题下的黑线 (位置不变) svg.append("line") .attr("x1", margin.left) .attr("y1", lineY) .attr("x2", width - margin.right) .attr("y2", lineY) .attr("stroke", "#000000") .attr("stroke-width", 1.5);
// 清理临时SVG元素 tempTextSvg.remove();
// ---------- 10. 创建主图表组 ----------
const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`);
// ---------- 11. 获取条形图颜色的辅助函数 ----------
// 获取条形图颜色 const getBarColor = (dimension) => { return colorResolver.field(dimension, 0, { fallback: colorResolver.other("primary", { fallback: "#83C341" }).value }).value; };
// 重命名函数,逻辑不变 (获取正方形/条形颜色) const getShapeColor = getBarColor;
// ---------- 13. 为每个维度绘制条形和正方形 ----------
sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension);
if (!dataPoint) { console.error(`No data found for dimension: ${dimension}`); return; }
// 检查数据值是否有效 if (isNaN(+dataPoint[valueField1]) || isNaN(+dataPoint[valueField2])) { console.error(`Invalid data values for ${dimension}: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; }
const barHeight = yScale.bandwidth(); const y = yScale(dimension); if (typeof y !== 'number') { console.error(`Invalid y position for dimension: ${dimension}`); return; }
const centerY = y + barHeight / 2; const barWidthValue = xScale(+dataPoint[valueField1]);
// 定义图标X坐标 const iconX = -(flagWidth + textPadding); // 图标放在最左侧,考虑padding
// 1. 添加图标(如果有) const iconGroup = g.append("g") .attr("transform", `translate(${iconX}, ${centerY - flagHeight/2})`);
if (images.field && images.field[dimension]) { iconGroup.append("image") .attr("x", -5) .attr("y", 0) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); } else { // 占位符 iconGroup.append("rect") .attr("width", flagWidth * 0.8) .attr("height", flagHeight * 0.8) .attr("x", flagWidth * 0.1) .attr("y", flagHeight * 0.1) .attr("fill", getShapeColor(dimension)) .attr("opacity", 0.6); }
// 2. 绘制条形(右侧圆角) const radius = barHeight / 2; const arcStartX = Math.max(0, barWidthValue - radius); g.append("path") .attr("d", `M 0,${y} L ${arcStartX},${y} A ${radius},${radius} 0 0,1 ${barWidthValue},${centerY} A ${radius},${radius} 0 0,1 ${arcStartX},${y + barHeight} L 0,${y + barHeight} Z`) .attr("fill", getBarColor(dimension)); // 直接使用颜色填充
// 3. 准备标签文本和测量宽度 const dimensionLabelText = dimension.toUpperCase(); const formattedValue1 = `${chartUtils.format.autoText(+dataPoint[valueField1])}${valueUnit1}`; const valueLabelFontSize = typography.label.font_size; const dimensionLabelFontSize = typography.label.font_size;
const countryLabelWidth = chartUtils.text.measure(g, dimensionLabelText, { fontFamily: typography.label.font_family, fontSize: dimensionLabelFontSize, fontWeight: typography.label.font_weight }).width;
const valueTextWidth = chartUtils.text.measure(g, formattedValue1, { fontFamily: typography.label.font_family, fontSize: valueLabelFontSize, fontWeight: typography.label.font_weight }).width;
// 4. 决定并绘制标签 let dimLabelX, dimLabelAnchor, dimLabelFill; let valueLabelX, valueLabelAnchor, valueLabelFill;
const canDimFitInside = barWidthValue >= countryLabelWidth + 2 * textPadding; // 左右各5px padding const canValueAlsoFitInside = barWidthValue >= textPadding + countryLabelWidth + textPadding + valueTextWidth + textPadding; // 多加一个标签间padding
if (canDimFitInside) { // 维度标签放内部左侧 dimLabelX = textPadding; dimLabelAnchor = "start"; dimLabelFill = "#FFFFFF"; g.append("text") .attr("x", dimLabelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", dimLabelAnchor) .style("font-family", typography.label.font_family) .style("font-size", dimensionLabelFontSize) .style("font-weight", typography.label.font_weight) .style("fill", dimLabelFill) .text(dimensionLabelText);
if (canValueAlsoFitInside) { // 数值标签放内部右侧 valueLabelX = barWidthValue - textPadding; valueLabelAnchor = "end"; valueLabelFill = "#FFFFFF"; } else { // 数值标签放外部右侧 valueLabelX = barWidthValue + textPadding; valueLabelAnchor = "start"; valueLabelFill = colorResolver.text({ fallback: "#333333" }).value; } // 绘制数值标签 g.append("text") .attr("x", valueLabelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", valueLabelAnchor) .style("font-family", typography.label.font_family) .style("font-size", valueLabelFontSize) .style("font-weight", typography.label.font_weight) .style("fill", valueLabelFill) .text(formattedValue1);
} else { // 维度标签放外部右侧 dimLabelX = barWidthValue + textPadding; dimLabelAnchor = "start"; dimLabelFill = colorResolver.text({ fallback: "#333333" }).value; const externalDimLabel = g.append("text") // 保存引用以获取宽度 .attr("x", dimLabelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", dimLabelAnchor) .style("font-family", typography.label.font_family) .style("font-size", dimensionLabelFontSize) .style("font-weight", typography.label.font_weight) .style("fill", dimLabelFill) .text(dimensionLabelText);
// 获取外部维度标签的实际渲染宽度 const externalDimLabelWidth = chartUtils.text.measure(g, dimensionLabelText, { fontFamily: typography.label.font_family, fontSize: dimensionLabelFontSize, fontWeight: typography.label.font_weight }).width;
// 数值标签放外部维度标签右侧 valueLabelX = dimLabelX + externalDimLabelWidth + labelGap; valueLabelAnchor = "start"; valueLabelFill = colorResolver.text({ fallback: "#333333" }).value; // 绘制数值标签 g.append("text") .attr("x", valueLabelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", valueLabelAnchor) .style("font-family", typography.label.font_family) .style("font-size", valueLabelFontSize) .style("font-weight", typography.label.font_weight) .style("fill", valueLabelFill) .text(formattedValue1); }
// 5. 绘制正方形和数值标签 const sideLength = squareSideScale(+dataPoint[valueField2]); const squareX = barChartWidth + circleChartWidth / 2 - sideLength / 2; // 水平居中 const squareY = y + barHeight / 2 - sideLength / 2; // 垂直居中 const squareFill = getShapeColor(dimension);
// 绘制正方形(无视觉效果) g.append("rect") .attr("x", squareX) .attr("y", squareY) .attr("width", sideLength) .attr("height", sideLength) .attr("fill", squareFill); // 直接使用颜色填充
// 添加正方形数值标签 const formattedValue2 = `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}`; const squareLabelFontSize = typography.label.font_size; // 使用label字体大小
const value2TextWidth = chartUtils.text.measure(g, formattedValue2, { fontFamily: typography.label.font_family, fontSize: squareLabelFontSize, fontWeight: typography.label.font_weight }).width;
// 判断文本是否能放入正方形内 let textFitsInSquare = (sideLength > value2TextWidth + 10); // 需要10px的内边距
if (textFitsInSquare) { // 文本放在正方形内,白色 g.append("text") .attr("x", squareX + sideLength / 2) // 居中 .attr("y", squareY + sideLength / 2) // 居中 .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", squareLabelFontSize) .style("font-weight", typography.label.font_weight) .style("fill", "#FFFFFF") .text(formattedValue2); } else { // 文本放在正方形上方,与正方形颜色相同 g.append("text") .attr("x", squareX + sideLength / 2) // 水平居中 .attr("y", squareY - 2) // 正方形上方一点 .attr("dy", "0em") .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", squareLabelFontSize) .style("font-weight", typography.label.font_weight) .style("fill", squareFill) // 与正方形同色 .text(formattedValue2); }
} catch (error) { console.error(`Error rendering chart element for ${dimension}:`, error); // Continue with the next item instead of stopping the entire chart } });
// 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_23", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary","secondary"], "supported_effects": ["gradient", "stroke", "radius_corner"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图与比例圆复合图表实现 - 使用D3.jshorizontal_bar_proportional_circle_area_chart_04function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // 1. 数据准备 const jsonData = data; // 完整JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置默认值 title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { text_color: "#FFFFFF", background_color: "#0A3B39", other: { primary: "#83C341" } }; const images = jsonData.images || { field: {}, other: {} }; // 图像配置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 const titles = jsonData.titles || {}; // 标题配置 // 清空容器 d3.select(containerSelector).html(""); // ---------- Temporary SVG for column title text measurement (defined early) ---------- const tempTextSvgForColumnTitles = d3.select(containerSelector) .append("svg").attr("width", 0).attr("height", 0).style("visibility", "hidden");
// ---------- Helper: Estimate Generic Text Width (for column titles) ---------- const estimateGenericTextWidth_forTitles = (text, fontConfig) => { return chartUtils.text.measure(tempTextSvgForColumnTitles, text, { fontFamily: fontConfig.font_family, fontSize: fontConfig.font_size, fontWeight: fontConfig.font_weight }).width; };
// ---------- Helper: Get Wrapped Lines (for column titles) ---------- function getWrappedLines_forTitles(textContent, availableWidth, fontConfig) { const words = (textContent || "").trim().split(/\s+/).filter(w => w !== ""); const lines = []; const fontSizeValue = parseFloat(fontConfig.font_size); const lineHeight = fontSizeValue * 1.2; // Estimate line height
if (words.length === 0) { return { linesArray: [], numLines: 0, lineHeight: lineHeight }; }
// Simplified single word breaking logic (breaks by char if too long) const breakSingleWord = (word) => { let currentWordPart = ""; const wordLines = []; for (let char of word) { if (estimateGenericTextWidth_forTitles(currentWordPart + char, fontConfig) > availableWidth && currentWordPart !== "") { wordLines.push(currentWordPart); currentWordPart = char; } else { currentWordPart += char; } } if (currentWordPart !== "") wordLines.push(currentWordPart); return wordLines.length > 0 ? wordLines : [word]; // Fallback to original word if wrapping fails };
if (words.length === 1) { if (estimateGenericTextWidth_forTitles(words[0], fontConfig) > availableWidth) { lines.push(...breakSingleWord(words[0])); } else { lines.push(words[0]); } return { linesArray: lines.filter(l=>l), numLines: lines.filter(l=>l).length, lineHeight: lineHeight }; } let currentLine = words[0]; if (estimateGenericTextWidth_forTitles(currentLine, fontConfig) > availableWidth) { const brokenFirstWord = breakSingleWord(currentLine); lines.push(...brokenFirstWord.slice(0, -1)); currentLine = brokenFirstWord.length > 0 ? brokenFirstWord[brokenFirstWord.length-1] : ""; }
for (let i = 1; i < words.length; i++) { const word = words[i]; if (estimateGenericTextWidth_forTitles(word, fontConfig) > availableWidth) { // Current word itself is too long if (currentLine !== "") lines.push(currentLine); lines.push(...breakSingleWord(word)); currentLine = ""; continue; }
const testLine = currentLine === "" ? word : currentLine + " " + word; if (estimateGenericTextWidth_forTitles(testLine, fontConfig) > availableWidth && currentLine !== "") { lines.push(currentLine); currentLine = word; } else { currentLine = testLine; } } if (currentLine !== "") { if (estimateGenericTextWidth_forTitles(currentLine, fontConfig) > availableWidth) { lines.push(...breakSingleWord(currentLine)); } else { lines.push(currentLine); } } return { linesArray: lines.filter(l=>l), numLines: lines.filter(l=>l).length, lineHeight: lineHeight }; }
// 2. 尺寸和布局设置 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 100, // 顶部标题空间 right: 5, // 右侧边距 bottom: 40, // 底部边距 left: 0 // 左侧边距(条形图紧贴左边) }; // 3. 提取字段名和单位 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : ""; // 列标题 const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 4. 数据处理 const sortedData = [...chartData].sort((a, b) => b[valueField1] - a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数
// 根据条形高度计算icon尺寸(便于其他模板复制复用) const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算)(便于其他模板复制复用) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
// 智能换行:优先按单词;利用率不足50%时尝试塞字母;长词断行加“-”;断词后下一行单字母开头尽量回并 const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; }; // 5. 布局计算 和 字体调整 const textPadding = 5; // 文本与图标/边缘的间距 const maxIconSize = 30; // Icon最大尺寸 const barPadding = 0.2; const dimLabelMaxWidth = width * 0.2; // 类别label允许占用的最大宽度(按图表总宽度比例) const dimLabelLineSpacing = 1.01; // 类别label行距系数(尽量紧凑)
// innerHeight 不依赖 margin.left,可先计算;yScale 用它计算条形高度与条间距(真实barGap) const innerHeight = height - margin.top - margin.bottom; const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
const barHeight = yScale.bandwidth(); const barGap = Math.max(0, yScale.step() - yScale.bandwidth()); // 条形之间的间距 const maxDimLabelHeight = barHeight + barGap; // 类别label整体高度上限
// icon尺寸(按barHeight动态) const iconSize = calcIconSize(barHeight, { maxSize: maxIconSize, minRatio: 0.8, minPx: 10 }); const flagWidth = iconSize.width; const flagHeight = iconSize.height;
// 类别label布局(统一字号+换行) const dimLabelLayout = buildDimLabelLayout({ containerSelector: containerSelector, labels: sortedDimensions, fontConfig: typography.label, maxWidth: dimLabelMaxWidth, maxHeight: maxDimLabelHeight, lineSpacing: dimLabelLineSpacing, targetFontSize: Math.min(20, barHeight * 0.6) }); const dimLabelConfig = dimLabelLayout.dimLabelConfig; const maxDimLabelWidth = dimLabelLayout.maxLabelWidth;
// 更新左边距(使用动态icon尺寸与最大label宽度) const requiredLeftSpace = maxDimLabelWidth + textPadding + flagWidth + textPadding; margin.left = requiredLeftSpace + 5;
// 设置条形图和圆形图的布局比例 const leftColumnRatio = 0.85; const rightColumnRatio = 0.15;
// 计算内部绘图区域尺寸(innerHeight已计算) const innerWidth = width - margin.left - margin.right;
// 计算两列的宽度 const barChartWidth = innerWidth * leftColumnRatio; const circleChartWidth = innerWidth * rightColumnRatio; // X轴比例尺(第一个数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, barChartWidth]); // 圆形面积比例尺(第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); const minRadius = yScale.bandwidth() * 0.3; // 最小半径 const maxRadius = Math.min(yScale.bandwidth() * 1.0, circleChartWidth*0.5) // 最大半径 const radiusScale = d3.scaleSqrt() // 使用平方根比例尺确保面积比例正确 .domain([0, maxValue2]) .range([minRadius, maxRadius]); // 7. 创建SVG容器 ( Titles will be appended to this directly) 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");
// 获取主题色 const primaryColor = colorResolver.other("primary", { fallback: "#83C341" }).value; // 添加defs用于视觉效果 const defs = svg.append("defs");
// 添加水平渐变(从左到右,匹配_02.js的最终版本) const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%");
gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.3 }));
gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 }));
// 8. 添加标题 (Refactored for wrapping) const titleFontConfig = typography.description; const titleBottomPadding = 5; // 标题底部与图表顶部(主绘图区g元素)之间的间距 const desiredBaselineOfLastLine = margin.top - titleBottomPadding; // g元素上方10px
// 左侧列标题 // Note: innerWidth here is calculated based on the dynamic margin.left from _23.js const leftTitleAvailableWidth = innerWidth * 0.6; const leftTitleXPos = margin.left; // Starts at the beginning of the main chart content area const wrappedLeftTitle = getWrappedLines_forTitles(columnTitle1, leftTitleAvailableWidth, titleFontConfig);
if (wrappedLeftTitle.numLines > 0) { const initialYLeft = desiredBaselineOfLastLine - (wrappedLeftTitle.numLines - 1) * wrappedLeftTitle.lineHeight; const leftTitleText = svg.append("text") // Append to svg, not g .attr("x", leftTitleXPos) .attr("y", initialYLeft) .attr("text-anchor", "start") .style("font-family", titleFontConfig.font_family) .style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
wrappedLeftTitle.linesArray.forEach((line, i) => { leftTitleText.append("tspan") .attr("x", leftTitleXPos) .attr("dy", i === 0 ? 0 : wrappedLeftTitle.lineHeight) .text(line); }); }
// 右侧列标题 const rightTitleAvailableWidth = innerWidth * 0.4; const rightTitleXPos = margin.left + innerWidth; // Right edge of the main chart content area const wrappedRightTitle = getWrappedLines_forTitles(columnTitle2, rightTitleAvailableWidth, titleFontConfig);
if (wrappedRightTitle.numLines > 0) { const initialYRight = desiredBaselineOfLastLine - (wrappedRightTitle.numLines - 1) * wrappedRightTitle.lineHeight; const rightTitleText = svg.append("text") // Append to svg, not g .attr("x", rightTitleXPos) .attr("y", initialYRight) .attr("text-anchor", "end") .style("font-family", titleFontConfig.font_family) .style("font-size", titleFontConfig.font_size) .style("font-weight", titleFontConfig.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
wrappedRightTitle.linesArray.forEach((line, i) => { rightTitleText.append("tspan") .attr("x", rightTitleXPos) .attr("dy", i === 0 ? 0 : wrappedRightTitle.lineHeight) .text(line); }); } // Remove the temporary SVG for column title measurement tempTextSvgForColumnTitles.remove();
// ---------- Helper: Estimate Text Width ---------- const tempTextSvg = svg.append("g").attr("visibility", "hidden"); const estimateLabelWidth = (text, fontConfig, barHeight) => { // Calculate dynamic font size for value labels if applicable const isValueLabel = fontConfig === typography.annotation; const fontSize = isValueLabel ? `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px` : fontConfig.font_size;
return chartUtils.text.measure(tempTextSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width; };
// ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制条形和标签 ---------- // 获取条形描边颜色 (匹配_02.js的最终版本) const getStrokeColor = (dimension) => { const baseColor = colorResolver.other("primary", { fallback: "#83C341" }).value; return colorResolver.variant(baseColor, { mode: "brighter", amount: 3 }); }; // 获取圆形图颜色 const getCircleColor = (dimension) => { return colorResolver.other("secondary", { fallback: "#83C341" }).value; // 亮绿色 };
// 存储第一个条形的宽度,用于后续条形图标签位置决策 let firstBarWidth = 0; if (sortedDimensions.length > 0) { const firstDataPoint = chartData.find(d => d[dimensionField] === sortedDimensions[0]); if (firstDataPoint) { firstBarWidth = xScale(+firstDataPoint[valueField1]); } } // 为每个维度绘制条形和圆形 sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (!dataPoint) { console.error(`No data found for dimension: ${dimension}`); return; } // 检查数据值是否有效 if (isNaN(+dataPoint[valueField1]) || isNaN(+dataPoint[valueField2])) { console.error(`Invalid data values for ${dimension}: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; } const barHeight = yScale.bandwidth(); const y = yScale(dimension); if (typeof y !== 'number') { console.error(`Invalid y position for dimension: ${dimension}`); return; } const centerY = y + barHeight / 2; const barWidthValue = Math.max(0, xScale(+dataPoint[valueField1])); //确保不为负
// --- 定义元素位置 (新布局) --- const labelX = -(flagWidth + textPadding + 5); const iconX = -flagWidth - 5;
// 1. 绘制条形 (强制视觉效果) (保持不变) g.append("rect") .attr("x", 0) .attr("y", y) .attr("width", barWidthValue) .attr("height", barHeight) .attr("fill", "url(#bar-gradient)") // 强制渐变填充 .attr("rx", barHeight/4) // 强制圆角半径4 .attr("ry", barHeight/4) // 强制圆角半径4 .attr("opacity", 0.9);
// 2. 添加维度标签 (支持多行换行,字符级断行,右对齐) const labelConfig = dimLabelConfig[dimension]; const labelGroup = g.append("text") .attr("x", labelX) .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
if (labelConfig.needsWrapping) { // 多行:使用“y + dy”的方式,和bar内数值label保持同一套定位体系,确保SVG/PNG一致 const lineHeight = labelConfig.lineHeight; const startY = centerY - ((labelConfig.lines.length - 1) * lineHeight) / 2; labelGroup.attr("y", startY);
labelConfig.lines.forEach((line, i) => { labelGroup.append("tspan") .attr("x", labelX) // 第一行用0.35em把baseline调到视觉居中位置;后续行用像素行高推进 .attr("dy", i === 0 ? "0.35em" : `${lineHeight}`) .text(line); }); } else { // 单行:与bar内数值label一致(y=centerY + dy=0.35em) labelGroup .attr("y", centerY) .attr("dy", "0.35em") .text(labelConfig.lines[0]); }
// 3. 添加图标 (新位置, 无裁剪) const iconGroup = g.append("g") .attr("transform", `translate(${iconX}, ${centerY - flagHeight/2})`);
if (images.field && images.field[dimension]) { // 绘制图片(无边框圆圈) iconGroup.append("image") .attr("x", 0) .attr("y", 0) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); // 不再需要clip-path } // 4. 添加条形数值标签 (需要重新评估位置逻辑) const valueLabelText = `${chartUtils.format.autoText(+dataPoint[valueField1])}${valueUnit1}`; const currentValueLabelWidth = estimateLabelWidth(valueLabelText, typography.annotation, barHeight); const valueLabelFontSize = `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`; // 定位逻辑:优先放内部左侧,如果放不下或者太拥挤,再放外部 let valueLabelXPos, valueLabelAnchor, valueLabelFill; const internalPadding = 10; // 内部所需间距 const externalPadding = 5; // 外部所需间距
if (barWidthValue >= currentValueLabelWidth + internalPadding * 2) { // 空间足够放内部,靠左显示 valueLabelXPos = internalPadding; // 靠左 valueLabelAnchor = "start"; valueLabelFill = "#FFFFFF"; } else { // 放外部 valueLabelXPos = barWidthValue + externalPadding; valueLabelAnchor = "start"; valueLabelFill = colorResolver.text({ fallback: "#333333" }).value; }
g.append("text") .attr("x", valueLabelXPos) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", valueLabelAnchor) .style("font-family", typography.annotation.font_family) .style("font-size", valueLabelFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", valueLabelFill) .text(valueLabelText);
// 5. 绘制圆形 (保持不变, 但注意其绝对X位置受margin.left影响) const circleRadius = radiusScale(+dataPoint[valueField2]); const circleX = barChartWidth + circleChartWidth / 2; g.append("circle") .attr("cx", circleX) .attr("cy", centerY) .attr("r", circleRadius) .attr("fill", getCircleColor(dimension)) .attr("opacity", 0.6);
// 6. 添加圆形数值标签 (GDP Value) const formattedValue2 = `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}`; const circleLabelFontSize = `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`; g.append("text") .attr("x", circleX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", circleLabelFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue2);
} catch (error) { console.error(`渲染${dimension}时出错:`, error); } });
// 移除临时SVG元素 tempTextSvg.remove();
// 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_24", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary","secondary"], "supported_effects": ["gradient", "radius_corner"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图与比例圆复合图表实现 - 使用D3.jshorizontal_bar_proportional_circle_area_chart_05function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // 1. 数据准备 const jsonData = data; // 完整JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置默认值 title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { text_color: "#FFFFFF", background_color: "#0A3B39", other: { primary: "#83C341" } }; const images = jsonData.images || { field: {}, other: {} }; // 图像配置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 const titles = jsonData.titles || {}; // 标题配置 // 清空容器 d3.select(containerSelector).html(""); // 2. 尺寸和布局设置 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 90, // 顶部标题空间 right: 10, // 右侧边距 bottom: 50, // 底部边距 left: 0 // 左侧边距(初始值,将根据标签和图标宽度调整) }; // 3. 提取字段名和单位 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : ""; // 列标题 const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 4. 数据处理 const sortedData = [...chartData].sort((a, b) => b[valueField1] - a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 // 5. 布局计算 和 字体调整 const flagWidth = 30; const flagHeight = 30; const textPadding = 5; // 文本与图标/边缘的间距 const minFontSize = 10; // 最小字体大小
let maxDimLabelWidth = 0; let defaultLabelFontSize = parseFloat(typography.label.font_size); sortedDimensions.forEach(dimension => { const labelText = dimension.toUpperCase(); const textWidth = chartUtils.text.measure(null, labelText, { fontFamily: typography.label.font_family, fontSize: `${defaultLabelFontSize}px`, fontWeight: typography.label.font_weight }).width; maxDimLabelWidth = Math.max(maxDimLabelWidth, textWidth); });
// 计算可用空间并调整字体大小 const maxAllowedLabelSpace = width * 0.20; // 允许标签占用的最大宽度比例 let finalDimLabelFontSize = defaultLabelFontSize; if (maxDimLabelWidth > maxAllowedLabelSpace) { const scaleFactor = maxAllowedLabelSpace / maxDimLabelWidth; finalDimLabelFontSize = Math.max(minFontSize, defaultLabelFontSize * scaleFactor); // 重新计算调整后的最大宽度 maxDimLabelWidth = 0; sortedDimensions.forEach(dimension => { const labelText = dimension.toUpperCase(); const textWidth = chartUtils.text.measure(null, labelText, { fontFamily: typography.label.font_family, fontSize: `${finalDimLabelFontSize}px`, fontWeight: typography.label.font_weight }).width; maxDimLabelWidth = Math.max(maxDimLabelWidth, textWidth); }); }
// 设置各区域宽度 - 更新为 _04.js 的逻辑 const requiredLeftSpace = maxDimLabelWidth + textPadding + flagWidth + textPadding; margin.left = requiredLeftSpace + 10; // 增加10px缓冲
// 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;
// 重新计算圆形图和条形图区域宽度(基于新的innerWidth) const circleAreaRatio = 0.25; // 圆形区域占内部宽度的比例 const barAreaRatio = 1 - circleAreaRatio; // 条形区域占内部宽度的比例 const circleAreaWidth = innerWidth * circleAreaRatio; const barAreaWidth = innerWidth * barAreaRatio;
// 6. 创建比例尺 const barPadding = 0.2; // Y轴比例尺(维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(第一个数值)- 范围调整为条形图区域宽度 const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, barAreaWidth]); // 使用 barAreaWidth // 圆形面积比例尺(第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); const minRadius = yScale.bandwidth() * 0.3; // 最小半径 // 调整最大半径以适应 circleAreaWidth const maxRadius = Math.min(yScale.bandwidth(), circleAreaWidth / 2); // 使用新的 circleAreaWidth const radiusScale = d3.scaleSqrt() // 使用平方根比例尺确保面积比例正确 .domain([0, maxValue2]) .range([minRadius, maxRadius]); // 7. 创建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");
// 获取主题色 const primaryColor = colorResolver.other("primary", { fallback: "#83C341" }).value; // 添加defs用于视觉效果 const defs = svg.append("defs");
// 添加水平渐变(从左到右) const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%");
gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.3 }));
gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 }));
// 条形图列标题 - 定位到条形图区域右侧 svg.append("text") .attr("x", margin.left + innerWidth) // 定位到内部区域右边缘 .attr("y", margin.top - 10) .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle1); // 圆形图列标题 - 定位到圆形图区域中心 svg.append("text") .attr("x", margin.left + circleAreaWidth / 2) // 定位到圆形区域中心 .attr("y", margin.top - 10) .attr("text-anchor", "middle") // 居中对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle2); // ---------- Helper: Estimate Text Width ---------- const estimateLabelWidth = (text, fontConfig, barHeight) => { // Calculate dynamic font size for value labels if applicable const isValueLabel = fontConfig === typography.annotation; const fontSize = isValueLabel ? `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px` : fontConfig.font_size;
return chartUtils.text.measure(svg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width; };
// ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制元素 ---------- // 获取条形描边颜色 const getStrokeColor = (dimension) => { const baseColor = colorResolver.other("primary", { fallback: "#83C341" }).value; return colorResolver.variant(baseColor, { mode: "brighter", amount: 3 }); }; // 获取圆形图颜色 const getCircleColor = (dimension) => { return colorResolver.other("secondary", { fallback: "#83C341" }).value; // 亮绿色 };
// 为每个维度绘制元素 sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (!dataPoint) { console.error(`No data found for dimension: ${dimension}`); return; } // 检查数据值是否有效 if (isNaN(+dataPoint[valueField1]) || isNaN(+dataPoint[valueField2])) { console.error(`Invalid data values for ${dimension}: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; } const barHeight = yScale.bandwidth(); const y = yScale(dimension); if (typeof y !== 'number') { console.error(`Invalid y position for dimension: ${dimension}`); return; } const centerY = y + barHeight / 2; const barWidthValue = Math.max(0, xScale(+dataPoint[valueField1])); // 确保不为负
// --- 重新定义元素位置 (借鉴 _04.js 标签/图标逻辑) --- // 1. 标签位于 G 元素的左侧 const labelX = -(flagWidth + textPadding + 5); // 相对 G 的 x 坐标 // 2. 图标位于 G 元素的左侧,标签右侧 const iconX = -(flagWidth + 5); // 相对 G 的 x 坐标 // 3. 圆形图位于内部绘图区域的左侧部分 (circleAreaWidth) const circleX = circleAreaWidth / 2; // 圆心位于圆形区域中间 // 4. 条形图位于内部绘图区域的右侧部分 (barAreaWidth),右对齐 const barAreaStartX = circleAreaWidth; // 条形区域开始的 X 坐标 (相对 G) const barX = barAreaStartX + barAreaWidth - barWidthValue; // 条形左上角 X (右对齐)
// 1. 添加维度标签 (移到左侧) g.append("text") .attr("x", labelX) // 使用新的 x 坐标 .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", `${finalDimLabelFontSize}px`) // 使用最终字体大小 .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension.toUpperCase());
// 2. 添加图标 (移到左侧) const iconGroup = g.append("g") .attr("transform", `translate(${iconX}, ${centerY - flagHeight/2})`); // 使用新的 x 坐标
if (images.field && images.field[dimension]) { // 绘制图片(移除边框圆圈) iconGroup.append("image") .attr("x", 0) .attr("y", 0) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); }
// 3. 绘制圆形 - 位置调整到 circleAreaWidth 内 const circleRadius = radiusScale(+dataPoint[valueField2]); g.append("circle") .attr("cx", circleX) // 使用新的 cx .attr("cy", centerY) .attr("r", circleRadius) .attr("fill", getCircleColor(dimension)) .attr("opacity", 0.6) .attr("stroke", "#FFFFFF") .attr("stroke-width", 1) .attr("stroke-opacity", 0.5);
// 4. 添加圆形数值标签 const formattedValue2 = `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}`; // 动态调整字体大小,确保适合圆圈 const circleLabelFontSize = Math.min( 14, Math.max(10, Math.min(barHeight * 0.5, circleRadius * 0.8)) ); g.append("text") .attr("x", circleX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", `${circleLabelFontSize}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue2);
// 5. 绘制条形 - 位置和宽度调整到 barAreaWidth 内,右对齐 g.append("rect") .attr("x", barX) // 使用新的 x 坐标 .attr("y", y) .attr("width", barWidthValue) // 宽度基于 xScale .attr("height", barHeight) .attr("fill", "url(#bar-gradient)") .attr("rx", barHeight/4) .attr("ry", barHeight/4) .attr("opacity", 0.9);
// 6. 添加条形数值标签 - 根据条形宽度智能放置 (坐标基于新的 barX) const valueLabelText = `${chartUtils.format.autoText(+dataPoint[valueField1])}${valueUnit1}`; const currentValueLabelWidth = estimateLabelWidth(valueLabelText, typography.annotation, barHeight); const valueLabelFontSize = Math.min(16, Math.max(barHeight * 0.5, 12)); // 确定标签位置:有足够空间时放在条形内部左侧,否则放在左侧外部 let valueLabelXPos, valueLabelAnchor, valueLabelFill; const internalPadding = 10; // 内部所需间距 const externalPadding = 8; // 外部所需间距
if (barWidthValue >= currentValueLabelWidth + internalPadding * 2) { // 空间足够放内部,靠左显示 valueLabelXPos = barX + internalPadding; // 基于新的 barX valueLabelAnchor = "start"; valueLabelFill = "#FFFFFF"; // 条形内部使用白色文本 } else { // 放外部 valueLabelXPos = barX - externalPadding; // 基于新的 barX valueLabelAnchor = "end"; valueLabelFill = colorResolver.text({ fallback: "#333333" }).value; }
g.append("text") .attr("x", valueLabelXPos) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", valueLabelAnchor) .style("font-family", typography.annotation.font_family) .style("font-size", `${valueLabelFontSize}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", valueLabelFill) .text(valueLabelText); } catch (error) { console.error(`渲染${dimension}时出错:`, error); } });
// 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_25", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [ ["categorical"], ["numerical"], ["numerical"] ], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": ["primary","secondary"], "supported_effects": ["radius_corner"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图与比例圆复合图表实现 - 使用D3.js 圆在左边function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // 1. 数据准备 const jsonData = data; // 完整JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置默认值 title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { // 颜色配置 text_color: "#FFFFFF", background_color: "#0A3B39", other: { primary: "#83C341", secondary: "#FFA500" } // 提供备用颜色 }; // const images = jsonData.images || { field: {}, other: {} }; // 不再需要图标配置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // const titles = jsonData.titles || {}; // 标题配置似乎未使用
// 设置视觉效果变量 (圆角由代码直接控制,不再需要此变量) // variables.has_rounded_corners = variables.has_rounded_corners || false;
// 清空容器 d3.select(containerSelector).html("");
// 2. 尺寸和布局设置 const width = variables.width || 800; const height = variables.height || 600;
// 设置边距 const margin = { top: 90, // 顶部标题空间 right: 10, // 右侧边距 bottom: 50, // 底部边距 left: 10 // 左侧边距(初始值,将根据标签宽度调整) };
// 3. 提取字段名和单位 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners";
// 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : "";
// 列标题 const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners";
// 4. 数据处理 const sortedData = [...chartData].sort((a, b) => b[valueField1] - a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 const tempSvgForEstimation = d3.select(containerSelector).append("svg").attr("width", 0).attr("height", 0).style("visibility", "hidden"); // 用于估算文本宽度
// ---------- Helper: Estimate Text Width ---------- const estimateLabelWidth = (text, fontConfig, defaultFontSize = 12) => { const fontSize = fontConfig.font_size || `${defaultFontSize}px`; const fontFamily = fontConfig.font_family || "Arial"; const fontWeight = fontConfig.font_weight || "normal";
return chartUtils.text.measure(tempSvgForEstimation, text, { fontFamily, fontSize, fontWeight }).width; };
// 5. 布局计算 const dimLabelPadding = 10; // 维度标签与左边缘的间距 const valueLabelExternalPadding = 3; // 数值标签与其对应条形图左侧的间距 const minFontSize = 10; // 最小字体大小 const gapBetweenCircleAndBar = 15; // 圆形区域和条形图区域之间的固定间隙
// 5.1 计算维度标签所需最大宽度和最终字体大小 let maxDimLabelWidth = 0; let defaultLabelFontSize = parseFloat(typography.label.font_size); sortedDimensions.forEach(dimension => { const labelText = dimension.toUpperCase(); maxDimLabelWidth = Math.max(maxDimLabelWidth, estimateLabelWidth(labelText, typography.label, defaultLabelFontSize)); });
const maxAllowedLabelSpace = width * 0.20; // 允许标签占用的最大宽度比例 let finalDimLabelFontSize = defaultLabelFontSize; if (maxDimLabelWidth > maxAllowedLabelSpace) { const scaleFactor = maxAllowedLabelSpace / maxDimLabelWidth; finalDimLabelFontSize = Math.max(minFontSize, defaultLabelFontSize * scaleFactor); // 重新计算调整后的最大宽度 maxDimLabelWidth = 0; sortedDimensions.forEach(dimension => { const labelText = dimension.toUpperCase(); maxDimLabelWidth = Math.max(maxDimLabelWidth, estimateLabelWidth(labelText, typography.label, finalDimLabelFontSize)); }); } tempSvgForEstimation.remove(); // 移除临时SVG
// 5.2 设置最终边距和内部尺寸 const requiredLeftSpace = maxDimLabelWidth + dimLabelPadding; // 仅需要标签宽度和内边距 margin.left = requiredLeftSpace + 10; // 增加10px缓冲 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;
// 5.3 划分内部绘图区域宽度 (圆形区 + 间隙 + 条形区) const circleAreaRatio = 0.25; // 圆形区域占内部宽度的比例 (相对于总innerWidth) const circleAreaWidth = innerWidth * circleAreaRatio; // 圆形区域宽度 let barAreaWidth = innerWidth - circleAreaWidth - gapBetweenCircleAndBar; // 剩余给条形图的宽度
// 确保条形图区域有最小宽度 const minBarWidth = 10; if (barAreaWidth < minBarWidth) { console.warn(`计算出的条形图区域宽度 (${barAreaWidth}px) 过小,已调整为最小值 ${minBarWidth}px。可能导致元素重叠或显示不佳。`); barAreaWidth = minBarWidth; }
// 6. 创建比例尺 const barPadding = 0.2;
// Y轴比例尺(维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
// X轴比例尺(第一个数值)- 范围是调整后的 barAreaWidth const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, barAreaWidth]); // 使用调整后的 barAreaWidth
// 圆形面积比例尺(第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); const minRadius = yScale.bandwidth() * 0.3; // 最小半径 const maxRadius = Math.min(yScale.bandwidth() * 0.45, circleAreaWidth / 2 - 5); // 避免贴边 const radiusScale = d3.scaleSqrt() .domain([0, maxValue2]) .range([minRadius, maxRadius]);
// 7. 创建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");
// 8. 绘制标题和坐标轴标签 (如果有) // 条形图列标题 - 定位到内部区域最右边缘 svg.append("text") .attr("x", margin.left + innerWidth) // 定位到内部区域右边缘 .attr("y", margin.top - 10) .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle1);
// 圆形图列标题 - 定位到圆形图区域中心 svg.append("text") .attr("x", margin.left + circleAreaWidth / 2) // 定位到圆形区域中心 .attr("y", margin.top - 10) .attr("text-anchor", "middle") // 居中对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle2);
// ---------- Helper: Get Bar Color ---------- const getBarColor = (dimension) => { return (colorResolver.field(dimension, 0, { fallbackKey: "primary" }).value) ? colorResolver.field(dimension, 0, { fallbackKey: "primary" }).value : (colorResolver.other("primary", { fallback: "#83C341" }).value); };
// ---------- Helper: Get Stroke Color ---------- const getStrokeColor = (dimension) => { const baseColor = getBarColor(dimension); try { return colorResolver.variant(baseColor, { mode: "brighter", amount: 3 }); } catch (error) { console.warn(`无法生成维度 ${dimension} 的描边颜色 (基础颜色: ${baseColor}): `, error); return baseColor; } };
// ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`);
// ---------- 10. 绘制元素 ----------
// 为每个维度绘制元素 sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension);
if (!dataPoint) { console.error(`找不到维度的数据: ${dimension}`); return; }
const value1 = +dataPoint[valueField1]; const value2 = +dataPoint[valueField2]; if (isNaN(value1) || isNaN(value2)) { console.error(`${dimension} 的数据值无效: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; }
const barHeight = yScale.bandwidth(); const y = yScale(dimension); if (typeof y !== 'number') { console.error(`维度 ${dimension} 的y坐标无效`); return; }
const centerY = y + barHeight / 2;
// --- 定义元素 X 坐标 (基于动态计算) --- const dimensionLabelX = -dimLabelPadding; // 维度标签 X (右边缘) const circleX = circleAreaWidth / 2; // 圆心 X const barAreaStartX = circleAreaWidth + gapBetweenCircleAndBar; // 条形图区域起始 X const barWidthValue = Math.max(0, xScale(value1)); // 条形图宽度 const barX = barAreaStartX + barAreaWidth - barWidthValue; // 条形图左上角 X (在 barArea 内右对齐) const valueLabelXPos = barX - valueLabelExternalPadding; // 数值标签 X (右边缘), 紧邻条形左侧
// 1. 添加维度标签 g.append("text") .attr("x", dimensionLabelX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", `${finalDimLabelFontSize}px`) // 使用最终字体大小 .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension.toUpperCase());
// 2. 绘制圆形 const circleRadius = radiusScale(value2); const circleFillColor = (colorResolver.field(dimension, 0, { fallbackKey: "primary" }).value) ? colorResolver.field(dimension, 0, { fallbackKey: "primary" }).value : (colorResolver.other("secondary", { fallback: "#A9A9A9" }).value); g.append("circle") .attr("cx", circleX) .attr("cy", centerY) .attr("r", circleRadius) .attr("fill", circleFillColor) .attr("opacity", 0.6) .attr("stroke", "#FFFFFF") .attr("stroke-width", 1) .attr("stroke-opacity", 0.5);
// 3. 添加圆形数值标签 const formattedValue2 = `${chartUtils.format.autoText(value2)}${valueUnit2}`; const circleLabelFontSize = Math.min(14, Math.max(10, Math.min(barHeight * 0.4, circleRadius * 0.8))); g.append("text") .attr("x", circleX) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", `${circleLabelFontSize}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue2);
// 4. 绘制条形 const barFillColor = getBarColor(dimension); g.append("rect") .attr("x", barX) .attr("y", y) .attr("width", barWidthValue) .attr("height", barHeight) .attr("fill", barFillColor) .attr("rx", barHeight * 0.5) // 半圆角 .attr("ry", barHeight * 0.5) // 半圆角 .attr("opacity", 0.9) .style("stroke", getStrokeColor(dimension)) // 描边 .style("stroke-width", 1);
// 5. 添加条形数值标签 (位置相对条形) const valueLabelText = `${chartUtils.format.autoText(value1)}${valueUnit1}`; const valueLabelFontSize = Math.min(16, Math.max(barHeight * 0.5, 12)); g.append("text") .attr("x", valueLabelXPos) // 使用相对条形的X坐标 .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "end") // 文本右对齐 .style("font-family", typography.annotation.font_family) .style("font-size", `${valueLabelFontSize}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) // 固定使用默认文本颜色 .text(valueLabelText);
} catch (error) { console.error(`渲染维度 ${dimension} 时出错:`, error); } });
// 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_26", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [["categorical"], ["numerical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": ["primary","secondary"], "supported_effects": ["gradient", "radius_corner"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图与比例圆复合图表实现 - 使用D3.js horizontal_bar_proportional_circle_area_chart_05function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // 1. 数据准备 const jsonData = data; // 完整JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置默认值 title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { text_color: "#FFFFFF", background_color: "#0A3B39", other: { primary: "#83C341" } }; const images = jsonData.images || { field: {}, other: {} }; // 图像配置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 const titles = jsonData.titles || {}; // 标题配置 // 清空容器 d3.select(containerSelector).html(""); // 2. 尺寸和布局设置 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 90, // 顶部标题空间 right: 10, // 右侧边距 bottom: 50, // 底部边距 left: 0 // 左侧边距(初始值,将根据标签和图标宽度调整) }; // 3. 提取字段名和单位 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : ""; // 列标题 const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 4. 数据处理 const sortedData = [...chartData].sort((a, b) => b[valueField1] - a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 // 5. 布局计算 和 字体调整 const flagWidth = 30; const flagHeight = 30; const textPadding = 5; // 文本与图标/边缘的间距 const minFontSize = 10; // 最小字体大小
let maxDimLabelWidth = 0; let defaultLabelFontSize = parseFloat(typography.label.font_size); sortedDimensions.forEach(dimension => { const labelText = dimension.toUpperCase(); const textWidth = chartUtils.text.measure(null, labelText, { fontFamily: typography.label.font_family, fontSize: `${defaultLabelFontSize}px`, fontWeight: typography.label.font_weight }).width; maxDimLabelWidth = Math.max(maxDimLabelWidth, textWidth); });
// 计算可用空间并调整字体大小 const maxAllowedLabelSpace = width * 0.20; // 允许标签占用的最大宽度比例 let finalDimLabelFontSize = defaultLabelFontSize; if (maxDimLabelWidth > maxAllowedLabelSpace) { const scaleFactor = maxAllowedLabelSpace / maxDimLabelWidth; finalDimLabelFontSize = Math.max(minFontSize, defaultLabelFontSize * scaleFactor); // 重新计算调整后的最大宽度 maxDimLabelWidth = 0; sortedDimensions.forEach(dimension => { const labelText = dimension.toUpperCase(); const textWidth = chartUtils.text.measure(null, labelText, { fontFamily: typography.label.font_family, fontSize: `${finalDimLabelFontSize}px`, fontWeight: typography.label.font_weight }).width; maxDimLabelWidth = Math.max(maxDimLabelWidth, textWidth); }); }
// 设置各区域宽度 - 更新为 _04.js 的逻辑 const requiredLeftSpace = maxDimLabelWidth + textPadding + flagWidth + textPadding; margin.left = requiredLeftSpace + 10; // 增加10px缓冲
// 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;
// 重新计算圆形图和条形图区域宽度(基于新的innerWidth) const circleAreaRatio = 0.25; // 圆形区域占内部宽度的比例 const barAreaRatio = 1 - circleAreaRatio; // 条形区域占内部宽度的比例 const circleAreaWidth = innerWidth * circleAreaRatio; const barAreaWidth = innerWidth * barAreaRatio;
// 6. 创建比例尺 const barPadding = 0.2; // Y轴比例尺(维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(第一个数值)- 范围调整为条形图区域宽度 const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, barAreaWidth]); // 使用 barAreaWidth // 正方形面积比例尺(第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); const minSide = yScale.bandwidth() * 0.05; // 最小边长 // 调整最大边长以适应 squareAreaWidth 和条目高度 const maxSide = Math.min(yScale.bandwidth() * 1.8, circleAreaWidth); // 使用新的 circleAreaWidth (现在代表正方形区域宽度) const sideScale = d3.scaleSqrt() // 使用平方根比例尺确保面积比例正确 .domain([0, maxValue2]) .range([minSide, maxSide]); // 7. 创建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");
// 获取主题色 const primaryColor = colorResolver.other("primary", { fallback: "#83C341" }).value; // 添加defs用于视觉效果 const defs = svg.append("defs");
// --- 为每个唯一条形图颜色定义渐变 --- const uniqueBarColors = [...new Set(chartData.map(d => { const dimension = d[dimensionField]; const defaultBarColor = colorResolver.other("primary", { fallback: "#83C341" }).value; return colorResolver.field(dimension, 0, { fallback: defaultBarColor }).value; }))];
uniqueBarColors.forEach(barColor => { // 清理颜色值以用作ID (移除#和任何非字母数字字符) const gradientId = `bar-gradient-${barColor.replace(/[^a-zA-Z0-9]/g, '')}`; const gradient = defs.append("linearGradient") .attr("id", gradientId) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") // 水平渐变 .attr("y2", "0%");
// 定义渐变,中间最亮,两边较暗 gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(barColor, { mode: "darker", amount: 0.5 })); // 可以调整暗度
gradient.append("stop") .attr("offset", "50%") .attr("stop-color", colorResolver.variant(barColor, { mode: "brighter", amount: 1.5 })); // 可以调整亮度
gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(barColor, { mode: "darker", amount: 0.5 })); // 与起始点相同暗度 }); // --- 渐变定义结束 ---
// 条形图列标题 - 定位到条形图区域右侧 svg.append("text") .attr("x", margin.left + innerWidth) // 定位到内部区域右边缘 .attr("y", margin.top - 10) .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle1); // 正方形图列标题 - 定位到正方形图区域中心 svg.append("text") .attr("x", margin.left + circleAreaWidth / 2) // 定位到正方形区域中心 .attr("y", margin.top - 10) .attr("text-anchor", "middle") // ��中对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle2); // ---------- Helper: Estimate Text Width ---------- const estimateLabelWidth = (text, fontConfig, barHeight) => { // Calculate dynamic font size for value labels if applicable const isValueLabel = fontConfig === typography.annotation; const fontSize = isValueLabel ? `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px` : fontConfig.font_size;
return chartUtils.text.measure(svg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width; };
// ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制元素 ---------- // 为每个维度绘制元素 sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (!dataPoint) { console.error(`No data found for dimension: ${dimension}`); return; } // 检查数据值是否有效 if (isNaN(+dataPoint[valueField1]) || isNaN(+dataPoint[valueField2])) { console.error(`Invalid data values for ${dimension}: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; } const barHeight = yScale.bandwidth(); const y = yScale(dimension); if (typeof y !== 'number') { console.error(`Invalid y position for dimension: ${dimension}`); return; } const centerY = y + barHeight / 2; const barWidthValue = Math.max(0, xScale(+dataPoint[valueField1])); // 确保不为负
// --- 重新定义元素位置 (借鉴 _04.js 标签/图标逻辑) --- // 1. 标签位于 G 元素的左侧 const labelX = -(flagWidth + textPadding + 5); // 相对 G 的 x 坐标 // 2. 图标位于 G 元素的左侧,标签右侧 const iconX = -(flagWidth + 5); // 相对 G 的 x 坐标 // 3. 正方形图位于内部绘图区域的左侧部分 (circleAreaWidth) const squareAreaCenterX = circleAreaWidth / 2; // 正方形区域中心 X 坐标 // 4. 条形图位于内部绘图区域的右侧部分 (barAreaWidth),右对齐 const barAreaStartX = circleAreaWidth; // 条形区域开始的 X 坐标 (相对 G) const barX = barAreaStartX + barAreaWidth - barWidthValue; // 条形左上角 X (右对齐)
// 1. 添加维度标签 (移到左侧) g.append("text") .attr("x", labelX) // 使用新的 x 坐标 .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", `${finalDimLabelFontSize}px`) // 使用最终字体大小 .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension.toUpperCase());
// 2. 添加图标 (移到左侧) const iconGroup = g.append("g") .attr("transform", `translate(${iconX}, ${centerY - flagHeight/2})`); // 使用新的 x 坐标
if (images.field && images.field[dimension]) { // 绘制图片(移除边框圆圈) iconGroup.append("image") .attr("x", 0) .attr("y", 0) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); }
// 3. 绘制正方形 - 位置调整到 circleAreaWidth (正方形区域) 内 const squareSide = sideScale(+dataPoint[valueField2]); const squareX = squareAreaCenterX - squareSide / 2; // 正方形左上角 x const squareY = centerY - squareSide / 2; // 正方形左上角 y
// --- 确定颜色 --- const defaultBarColor = colorResolver.other("primary", { fallback: "#83C341" }).value; const defaultSquareColor = colorResolver.other("secondary", { fallback: "#57A0D3" }).value; // 使用不同的默认色以区分 const barColor = colorResolver.field(dimension, 0, { fallback: defaultBarColor }).value; const squareColor = colorResolver.field(dimension, 0, { fallback: defaultSquareColor }).value; // --- 确定颜色结束 ---
g.append("rect") // 绘制矩形代表正方形 .attr("x", squareX) .attr("y", squareY) .attr("width", squareSide) .attr("height", squareSide) .attr("fill", squareColor) // 使用维度特定颜色 .attr("opacity", 0.7) // 轻微调整不透明度以便区分 .attr("stroke", "#FFFFFF") .attr("stroke-width", 1) .attr("stroke-opacity", 0.5);
// 4. 添加正方形数值标签 - 根据大小决定位置和颜色 const formattedValue2 = `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}`; // 动态调整字体大小,确保适合正方形 const squareLabelFontSize = Math.min( 16, Math.max(12, Math.min(barHeight * 0.5, squareSide * 0.7)) // 基于 squareSide 调整 ); // 定义标签位置和颜色的阈值 const labelPositionThreshold = barHeight * 0.4; // 当边长大于此值时,标签在内部 let squareLabelFill, squareLabelX, squareLabelY, squareLabelAnchor, squareLabelDy;
if (squareSide >= labelPositionThreshold) { // 大正方形:标签在内部,白色 squareLabelFill = "#FFFFFF"; squareLabelX = squareAreaCenterX; squareLabelY = centerY; squareLabelAnchor = "middle"; squareLabelDy = "0.35em"; } else { // 小正方形:标签在上方,与正方形同色 squareLabelFill = squareColor; // 使用正方形的颜色 squareLabelX = squareAreaCenterX; squareLabelY = squareY - 5; // 放置在正方形顶部上方一点 squareLabelAnchor = "middle"; squareLabelDy = "0em"; // 基线对齐 }
g.append("text") .attr("x", squareLabelX) // 使用计算出的 X .attr("y", squareLabelY) // 使用计算出的 Y .attr("dy", squareLabelDy) // 使用计算出的 dy .attr("text-anchor", squareLabelAnchor) // 使用计算出的 text-anchor .style("font-family", typography.annotation.font_family) .style("font-size", `${squareLabelFontSize}px`) // 使用新的字体大小 .style("font-weight", typography.annotation.font_weight) .style("fill", squareLabelFill) // 使用计算出的 fill .text(formattedValue2);
// 5. 绘制条形 - 位置和宽度调整到 barAreaWidth 内,右对齐 g.append("rect") .attr("x", barX) // 使用新的 x 坐标 .attr("y", y) .attr("width", barWidthValue) // 宽度基于 xScale .attr("height", barHeight) // .attr("fill", barColor) // 移除直接颜色填充 .attr("fill", `url(#bar-gradient-${barColor.replace(/[^a-zA-Z0-9]/g, '')})`) // 应用对应的渐变 .attr("rx", barHeight/8) .attr("ry", barHeight/8) .attr("opacity", 0.9); // .attr("stroke", colorResolver.variant(barColor, { mode: "brighter", amount: 1 })) // 可选:添加基于填充色的描边 // .attr("stroke-width", 1);
// 6. 添加条形数值标签 - 根据条形宽度智能放置 (坐标基于新的 barX) const valueLabelText = `${chartUtils.format.autoText(+dataPoint[valueField1])}${valueUnit1}`; const currentValueLabelWidth = estimateLabelWidth(valueLabelText, typography.annotation, barHeight); const valueLabelFontSize = Math.min(16, Math.max(barHeight * 0.5, 12)); // 确定标签位置:有足够空间时放在条形内部左侧,否则放在左侧外部 let valueLabelXPos, valueLabelAnchor, valueLabelFill; const internalPadding = 10; // 内部所需间距 const externalPadding = 8; // 外部所需间距
if (barWidthValue >= currentValueLabelWidth + internalPadding * 2) { // 空间足够放内部,靠左显示 valueLabelXPos = barX + internalPadding; // 基于新的 barX valueLabelAnchor = "start"; valueLabelFill = "#FFFFFF"; // 条形内部使用白色文本 } else { // 放外部 valueLabelXPos = barX - externalPadding; // 基于新的 barX valueLabelAnchor = "end"; valueLabelFill = colorResolver.text({ fallback: "#333333" }).value; }
g.append("text") .attr("x", valueLabelXPos) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", valueLabelAnchor) .style("font-family", typography.annotation.font_family) .style("font-size", `${valueLabelFontSize}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", valueLabelFill) .text(valueLabelText); } catch (error) { console.error(`渲染${dimension}时出错:`, error); } });
// 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart With Circle", "chart_name": "horizontal_bar_chart_27", "is_composite": true, "required_fields": ["x", "y", "y2"], "required_fields_type": [["categorical"],["numerical"],["numerical"]], "required_fields_range": [[2, 30], [0, "inf"], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": ["primary","secondary"], "supported_effects": ["gradient", "radius_corner"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图与比例正方形复合图表实现 - 使用D3.js horizontal_bar_proportional_square_area_chart (基于 26 修改)function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // 1. 数据准备 const jsonData = data; // 完整JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置默认值 title: { font_family: "Arial", font_size: "28px", font_weight: 700 }, label: { font_family: "Arial", font_size: "16px", font_weight: 500 }, description: { font_family: "Arial", font_size: "16px", font_weight: 500 }, annotation: { font_family: "Arial", font_size: "12px", font_weight: 400 } }; const colors = jsonData.colors || { text_color: "#FFFFFF", background_color: "#0A3B39", other: { primary: "#83C341" } }; const images = jsonData.images || { field: {}, other: {} }; // 图像配置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 const titles = jsonData.titles || {}; // 标题配置 // 清空容器 d3.select(containerSelector).html(""); // 2. 尺寸和布局设置 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 90, // 顶部标题空间 right: 10, // 右侧边距 bottom: 50, // 底部边距 left: 0 // 左侧边距(初始值,将根据标签和图标宽度调整) }; // 3. 提取字段名和单位 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "Country"; const valueField1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const valueField2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 获取字段单位 let valueUnit1 = chartUtils.schema.channel(jsonData, "y").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y").unit; let valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none"? "" : chartUtils.schema.channel(jsonData, "y2").unit; valueUnit1 = valueUnit1 ? valueUnit1 : ""; valueUnit2 = valueUnit2 ? valueUnit2 : ""; // 列标题 const columnTitle1 = chartUtils.schema.channel(jsonData, "y").key || "Crypto Ownership Percentage"; const columnTitle2 = chartUtils.schema.channel(jsonData, "y2").key || "Number of Owners"; // 4. 数据处理 const sortedData = [...chartData].sort((a, b) => b[valueField1] - a[valueField1]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 // 5. 布局计算 和 字体调整 const flagWidth = 30; const flagHeight = 30; const textPadding = 5; // 文本与图标/边缘的间距 const minFontSize = 10; // 最小字体大小
let maxDimLabelWidth = 0; let defaultLabelFontSize = parseFloat(typography.label.font_size); sortedDimensions.forEach(dimension => { const labelText = dimension.toUpperCase(); const textWidth = chartUtils.text.measure(null, labelText, { fontFamily: typography.label.font_family, fontSize: `${defaultLabelFontSize}px`, fontWeight: typography.label.font_weight }).width; maxDimLabelWidth = Math.max(maxDimLabelWidth, textWidth); });
// 计算可用空间并调整字体大小 const maxAllowedLabelSpace = width * 0.20; // 允许标签占用的最大宽度比例 let finalDimLabelFontSize = defaultLabelFontSize; if (maxDimLabelWidth > maxAllowedLabelSpace) { const scaleFactor = maxAllowedLabelSpace / maxDimLabelWidth; finalDimLabelFontSize = Math.max(minFontSize, defaultLabelFontSize * scaleFactor); // 重新计算调整后的最大宽度 maxDimLabelWidth = 0; sortedDimensions.forEach(dimension => { const labelText = dimension.toUpperCase(); const textWidth = chartUtils.text.measure(null, labelText, { fontFamily: typography.label.font_family, fontSize: `${finalDimLabelFontSize}px`, fontWeight: typography.label.font_weight }).width; maxDimLabelWidth = Math.max(maxDimLabelWidth, textWidth); }); }
// 设置各区域宽度 - 移除图标空间 const requiredLeftSpace = maxDimLabelWidth + textPadding; // 只需标签和边距 margin.left = requiredLeftSpace ; // 增加10px缓冲
// 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;
// 重新计算圆形图和条形图区域宽度(基于新的innerWidth) const circleAreaRatio = 0.25; // 圆形区域占内部宽度的比例 const barAreaRatio = 1 - circleAreaRatio; // 条形区域占内部宽度的比例 const circleAreaWidth = innerWidth * circleAreaRatio; const barAreaWidth = innerWidth * barAreaRatio;
// 6. 创建比例尺 const barPadding = 0.2; // Y轴比例尺(维度) - 先定义 yScale 以计算 barHeight const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // 计算 barHeight 和 valueLabelFontSize 以便估算宽度 const barHeight = yScale.bandwidth(); const valueLabelFontSize = Math.min(20, Math.max(barHeight * 0.5, 12)); // 4.3 测量数值标签的最大宽度 const valueWidths = sortedData.map(d => { return chartUtils.text.measure(null, `${chartUtils.format.autoText(+d[valueField1])}${valueUnit1}`, { fontFamily: typography.annotation.font_family, fontSize: `${valueLabelFontSize}px`, fontWeight: typography.annotation.font_weight }).width; }); // 计算条形图可用的实际宽度 const availableBarWidth = Math.max(0, barAreaWidth - valueWidths[0] - textPadding); // X轴比例尺(第一个数值)- 范围调整为 availableBarWidth const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField1]) * 1.05]) // 添加5%边距 .range([0, availableBarWidth]); // 使用调整后的可用宽度 // 正方形面积比例尺(第二个数值) const maxValue2 = d3.max(chartData, d => +d[valueField2]); const minSide = yScale.bandwidth() * 0.05; // 最小边长 // 调整最大边长以适应 squareAreaWidth 和条目高度 const maxSide = Math.min(yScale.bandwidth() * 1.8, circleAreaWidth); // 使用新的 circleAreaWidth (现在代表正方形区域宽度) const sideScale = d3.scaleSqrt() // 使用平方根比例尺确保面积比例正确 .domain([0, maxValue2]) .range([minSide, maxSide]); // 7. 创建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");
// 获取主题色 const primaryColor = colorResolver.other("primary", { fallback: "#83C341" }).value; const secondaryColor = colorResolver.other("secondary", { fallback: "#57A0D3" }).value; // 添加defs用于视觉效果 const defs = svg.append("defs");
// --- 移除渐变定义代码 --- /* // --- 为每个唯一条形图颜色定义渐变 (基于维度颜色或 secondaryColor) --- const uniqueBarColors = [...new Set(chartData.map(d => { const dimension = d[dimensionField]; // 后备颜色使用 secondaryColor return colorResolver.field(dimension, 0, { fallback: secondaryColor }).value; }))];
uniqueBarColors.forEach(barColor => { // 清理颜色值以用作ID (移除#和任何非字母数字字符) const gradientId = `bar-gradient-${barColor.replace(/[^a-zA-Z0-9]/g, '')}`; const gradient = defs.append("linearGradient") .attr("id", gradientId) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") // 水平渐变 .attr("y2", "0%");
// 定义渐变,中间最亮,两边较暗 gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(barColor, { mode: "darker", amount: 0.5 })); // 可以调整暗度 gradient.append("stop") .attr("offset", "50%") .attr("stop-color", colorResolver.variant(barColor, { mode: "brighter", amount: 1.5 })); // 可以调整亮度 gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(barColor, { mode: "darker", amount: 0.5 })); // 与起始点相同暗度 }); // --- 渐变定义结束 --- */ // 条形图列标题 - 定位到条形图区域右侧 svg.append("text") .attr("x", margin.left + innerWidth) // 定位到内部区域右边缘 .attr("y", margin.top - 10) .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle1); // 正方形图列标题 - 定位到正方形图区域中心 svg.append("text") .attr("x", margin.left + circleAreaWidth / 2) // 定位到正方形区域中心 .attr("y", margin.top - 10) .attr("text-anchor", "middle") // 居中对齐 .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(columnTitle2); // ---------- Helper: Estimate Text Width ---------- const estimateLabelWidth = (text, fontConfig, barHeight) => { // Calculate dynamic font size for value labels if applicable const isValueLabel = fontConfig === typography.annotation; const fontSize = isValueLabel ? `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px` : fontConfig.font_size;
return chartUtils.text.measure(svg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width; };
// ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制元素 ---------- // 获取条形图颜色的辅助函数 const getBarColor = (dimension) => { return colorResolver.field(dimension, 0, { fallback: secondaryColor }).value; }; // 获取描边颜色的辅助函数 (来自用户) const getStrokeColor = (dimension) => { // 获取条形的基础颜色 const baseColor = getBarColor(dimension); // 返回该颜色的更亮版本 return colorResolver.variant(baseColor, { mode: "brighter", amount: 3 }); }; // 为每个维度绘制元素 sortedDimensions.forEach((dimension, index) => { try { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (!dataPoint) { console.error(`No data found for dimension: ${dimension}`); return; } // 检查数据值是否有效 if (isNaN(+dataPoint[valueField1]) || isNaN(+dataPoint[valueField2])) { console.error(`Invalid data values for ${dimension}: ${dataPoint[valueField1]}, ${dataPoint[valueField2]}`); return; } const barHeight = yScale.bandwidth(); const y = yScale(dimension); if (typeof y !== 'number') { console.error(`Invalid y position for dimension: ${dimension}`); return; } const centerY = y + barHeight / 2; const barWidthValue = Math.max(0, xScale(+dataPoint[valueField1])); // 确保不为负
// --- 重新定义元素位置 (无图标) --- // 1. 标签位于 G 元素的左侧 const labelX = -(textPadding); // 相对 G 的 x 坐标 (无图标宽度) // 2. 正方形图位于内部绘图区域的左侧部分 (circleAreaWidth) const squareAreaCenterX = circleAreaWidth / 2; // 正方形区域中心 X 坐标 // 3. 条形图位于内部绘图区域的右侧部分 (barAreaWidth),右对齐 const barAreaStartX = circleAreaWidth; // 条形区域开始的 X 坐标 (相对 G) const barX = barAreaStartX + barAreaWidth - barWidthValue; // 条形左上角 X (右对齐)
// 1. 添加维度标签 (移到左侧) g.append("text") .attr("x", labelX) // 使用新的 x 坐标 .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "end") // 右对齐 .style("font-family", typography.label.font_family) .style("font-size", `${finalDimLabelFontSize}px`) // 使用最终字体大小 .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension.toUpperCase());
// 3. 绘制正方形 - 位置调整到 circleAreaWidth (正方形区域) 内 const squareSide = sideScale(+dataPoint[valueField2]); const squareX = squareAreaCenterX - squareSide / 2; // 正方形左上角 x const squareY = centerY - squareSide / 2; // 正方形左上角 y
// --- 确定颜色 (正方形固定 primary, 条形图基于维度或 secondary) --- // const barColor = getBarColor(dimension); // 在绘制时获取 // const squareColor = primaryColor; // 正方形颜色直接使用 primaryColor // --- 颜色确定结束 ---
g.append("rect") // 绘制矩形代表正方形 .attr("x", squareX) .attr("y", squareY) .attr("width", squareSide) .attr("height", squareSide) .attr("fill", primaryColor) // 使用 primary 颜色 .attr("opacity", 0.7) // 轻微调整不透明度以便区分 .attr("stroke", "#FFFFFF") .attr("stroke-width", 1) .attr("stroke-opacity", 0.5);
// 4. 添加正方形数值标签 - 根据大小决定位置和颜色 const formattedValue2 = valueUnit2 ? `${chartUtils.format.autoText(+dataPoint[valueField2])}${valueUnit2}` : `${chartUtils.format.autoText(+dataPoint[valueField2])}`; // 动态调整字体大小,确保适合正方形 const squareLabelFontSize = Math.min( 16, Math.max(12, Math.min(barHeight * 0.5, squareSide * 0.7)) // 基于 squareSide 调整 ); // 定义标签位置和颜色的阈值 const labelPositionThreshold = barHeight * 0.4; // 当边长大于此值时,标签在内部 let squareLabelFill, squareLabelX, squareLabelY, squareLabelAnchor, squareLabelDy;
if (squareSide >= labelPositionThreshold) { // 大正方形:标签在内部,白色 squareLabelFill = "#FFFFFF"; squareLabelX = squareAreaCenterX; squareLabelY = centerY; squareLabelAnchor = "middle"; squareLabelDy = "0.35em"; } else { // 小正方形:标签在上方,与正方形同色 squareLabelFill = primaryColor; // 使用 primary 颜色 squareLabelX = squareAreaCenterX; squareLabelY = squareY - 5; // 放置在正方形顶部上方一点 squareLabelAnchor = "middle"; squareLabelDy = "0em"; // 基线对齐 }
g.append("text") .attr("x", squareLabelX) // 使用计算出的 X .attr("y", squareLabelY) // 使用计算出的 Y .attr("dy", squareLabelDy) // 使用计算出的 dy .attr("text-anchor", squareLabelAnchor) // 使用计算出的 text-anchor .style("font-family", typography.annotation.font_family) .style("font-size", `${squareLabelFontSize}px`) // 使用新的字体大小 .style("font-weight", typography.annotation.font_weight) .style("fill", squareLabelFill) // 使用计算出的 fill .text(formattedValue2);
// 5. 绘制条形 - 位置和宽度调整到 barAreaWidth 内,右对齐 const barColor = getBarColor(dimension); // 获取当前 bar 颜色 const strokeColor = getStrokeColor(dimension); // 获取当前 stroke 颜色 g.append("rect") .attr("x", barX) // 使用新的 x 坐标 .attr("y", y) .attr("width", barWidthValue) // 宽度基于 xScale .attr("height", barHeight) .attr("fill", barColor) // 直接使用 barColor 填充 .attr("stroke", strokeColor) // 添加描边颜色 .attr("stroke-width", 1.5) // 设置描边宽度 .attr("rx", barHeight/8) .attr("ry", barHeight/8) .attr("opacity", 0.9);
// 6. 添加条形数值标签 - 固定放在条形左侧外部 const formattedValue1 = valueUnit1 ? `${chartUtils.format.autoText(+dataPoint[valueField1])}${valueUnit1}` : `${chartUtils.format.autoText(+dataPoint[valueField1])}`; const valueLabelXPos = barX - textPadding; // 固定在条形左侧 const valueLabelAnchor = "end"; // 右对齐 const valueLabelFill = colorResolver.text({ fallback: "#333333" }).value; // 固定文本颜色
g.append("text") .attr("x", valueLabelXPos) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", valueLabelAnchor) .style("font-family", typography.annotation.font_family) .style("font-size", `${valueLabelFontSize}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", valueLabelFill) .text(formattedValue1); } catch (error) { console.error(`渲染${dimension}时出错:`, error); } });
// 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_28", "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": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "gradient", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.jsfunction makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; // 提取维度字段 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; // 获取数据维度数量 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; const dimensionCount = dimensions.length; // 设置边距 const margin = { top: 90, // 顶部留出标题空间 right: 120, // 右侧足够显示标签 bottom: 60, // 底部边距 left: 100 // 左侧空间 }; // 计算每个条形的理想高度 - 最小为64像素,最大为128像素 const MIN_BAR_HEIGHT = 64; const MAX_BAR_HEIGHT = 128; const barPadding = variables.has_spacing ? 20 : 10; // 计算条形高度,使用合理的默认值 const barHeight = Math.min(MAX_BAR_HEIGHT, Math.max(MIN_BAR_HEIGHT, 80)); // 默认80像素高 // 计算总的条形空间需求 const totalBarSpace = (barHeight + barPadding) * dimensionCount; // 计算图表所需的最小高度 (条形总高度 + 标题和底部的空间) const extraSpace = 150; // 为标题和底部空间预留的额外高度 const minHeight = variables.min_height || 400; const calculatedHeight = Math.max(minHeight, totalBarSpace + extraSpace); // 使用计算值或用户指定值作为最终高度 const height = variables.height || calculatedHeight; // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // 根据实际可用空间,可能需要调整条形高度 const availableHeight = innerHeight - 50; // 保留一些间距 const adjustedBarHeight = Math.min( barHeight, Math.max(MIN_BAR_HEIGHT, availableHeight / dimensionCount) ); // 使用调整后的条形高度 const finalBarHeight = adjustedBarHeight; const totalBarSpaceAdjusted = (finalBarHeight + barPadding) * dimensionCount; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ---------- // 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数
// 计算图标尺寸 const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
// 智能换行:优先按单词;利用率不足50%时尝试塞字母;长词断行加"-";断词后下一行单字母开头尽量回并 const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; };
// ---------- 5. 计算智能换行标签布局 ----------
// 提取label字体的基础尺寸 const labelFontSizeNum = parseInt(typography.label.font_size) || 12;
// 调用智能换行布局计算 const labelLayout = buildDimLabelLayout({ containerSelector, labels: dimensions, fontConfig: typography.label, maxWidth: 150, maxHeight: finalBarHeight, lineSpacing: 1.2, targetFontSize: labelFontSizeNum });
const dimLabelConfig = labelLayout.dimLabelConfig; const maxLabelWidth = labelLayout.maxLabelWidth;
// 根据标签宽度调整边距 margin.right = Math.max(margin.right, maxLabelWidth + 30); // ---------- 6. 创建比例尺 ---------- // 计算条形的额外间距(如果启用) const barScalePadding = variables.has_spacing ? 0.3 : 0.2; // 计算实际需要的总高度(基于调整后的条形高度) const actualNeededHeight = (finalBarHeight + barPadding) * dimensionCount; // 确保Y轴比例尺使用基于finalBarHeight计算的适当范围 // 如果actualNeededHeight小于innerHeight,则居中显示 const yAxisStart = Math.max(0, (innerHeight - actualNeededHeight) / 2); const yAxisEnd = Math.min(innerHeight, yAxisStart + actualNeededHeight); // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([yAxisStart, yAxisEnd]) .padding(barScalePadding); // X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添���5%边距 .range([0, innerWidth]);
// ---------- 7. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 添加渐变(如果启用) if (variables.has_gradient) { const primaryColor = colorResolver.other("primary", { fallback: "#882e2e" }).value; const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.3 })); } // ---------- 8. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 9. 绘制条形和标签 ---------- // 获取条形颜色的辅助函数 const getBarColor = () => { return colorResolver.other("primary", { fallback: "#882e2e" }).value; // 默认暗红色 }; // 绘制条形和标签 sortedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barBandHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]); const y = yScale(dimension); const centerY = y + barBandHeight / 2; // 创建条形组 const barGroup = g.append("g"); // 绘制矩形条形(没有圆角和边框) barGroup.append("rect") .attr("x", 0) .attr("y", y) .attr("width", barWidth) .attr("height", barBandHeight) .attr("fill", variables.has_gradient ? "url(#bar-gradient)" : getBarColor()) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); }); // 准备图标尺寸 const iconSize = barBandHeight * 0.7; const iconX = 0; const iconY = y + (barBandHeight - iconSize) / 2; // 添加图标(如果有)- 带白色圆形背景 if (images.field && images.field[dimension]) { // 添加白色圆形背景 barGroup.append("circle") .attr("cx", iconX + iconSize/2) .attr("cy", iconY + iconSize/2) .attr("r", iconSize/2) .attr("fill", "white"); // 添加图标 barGroup.append("image") .attr("x", iconX) .attr("y", iconY) .attr("width", iconSize) .attr("height", iconSize) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // 格式化数值用于显示 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; // 计算动态字体大小(条形高度的60%) const dynamicFontSize = `${barBandHeight * 0.6}px`; // 创建临时文本测量数值标签宽度(使用动态字体大小) const valueTextWidth = chartUtils.text.measure(svg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: dynamicFontSize, fontWeight: typography.annotation.font_weight }).width; // 判断数值标签是否能放入条形内 const labelFitsInside = valueTextWidth + 10 < barWidth; // 添加数值标签(使用动态字体大小) if (labelFitsInside) { // 标签放在条形内部 barGroup.append("text") .attr("x", barWidth - 5) .attr("y", y + barBandHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "end") .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", "#FFFFFF") // 白色 .text(formattedValue); } else { // 标签放在条形外部 barGroup.append("text") .attr("x", barWidth + 5) .attr("y", y + barBandHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) // 使用文本颜色 .text(formattedValue); }
// 添加维度标签(支持多行换行) const labelConfig = dimLabelConfig[dimension]; const labelX = barWidth + (labelFitsInside ? 5 : valueTextWidth + 15); const labelGroup = barGroup.append("text") .attr("x", labelX) .attr("text-anchor", "start") .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
if (labelConfig.needsWrapping) { const lineHeight = labelConfig.lineHeight; const startY = centerY - ((labelConfig.lines.length - 1) * lineHeight) / 2; labelGroup.attr("y", startY);
labelConfig.lines.forEach((line, i) => { labelGroup.append("tspan") .attr("x", labelX) .attr("dy", i === 0 ? "0.35em" : `${lineHeight}`) .text(line); }); } else { labelGroup .attr("y", centerY) .attr("dy", "0.35em") .text(labelConfig.lines[0]); }
// 在第一个条形上显示单位(如果有) if (index === 0 && valueUnit) { barGroup.append("text") .attr("x", barWidth) .attr("y", y - 5) // 条形顶部上方 .attr("text-anchor", "end") .style("font-family", typography.annotation.font_family) .style("font-size", typography.annotation.font_size) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(`(${valueUnit})`); } } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_29", "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": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "gradient", "spacing"], "min_height": 400, "min_width": 400, "background": "dark", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.jsfunction makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors_dark || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; // 提取维度字段 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; // 获取数据维度数量 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; const dimensionCount = dimensions.length; // 设置边距 const margin = { top: 90, // 顶部留出标题空间 right: 120, // 右侧足够显示标签 bottom: 60, // 底部边距 left: 100 // 左侧空间 }; // 计算每个条形的理想高度 - 最小为64像素,最大为128像素 const MIN_BAR_HEIGHT = 64; const MAX_BAR_HEIGHT = 128; const barPadding = variables.has_spacing ? 20 : 10; // 计算条形高度,使用合理的默认值 const barHeight = Math.min(MAX_BAR_HEIGHT, Math.max(MIN_BAR_HEIGHT, 80)); // 默认80像素高 // 计算总的条形空间需求 const totalBarSpace = (barHeight + barPadding) * dimensionCount; // 计算图表所需的最小高度 (条形总高度 + 标题和底部的空间) const extraSpace = 150; // 为标题和底部空间预留的额外高度 const minHeight = variables.min_height || 400; const calculatedHeight = Math.max(minHeight, totalBarSpace + extraSpace); // 使用计算值或用户指定值作为最终高度 const height = variables.height || calculatedHeight; // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // 根据实际可用空间,可能需要调整条形高度 const availableHeight = innerHeight - 50; // 保留一些间距 const adjustedBarHeight = Math.min( barHeight, Math.max(MIN_BAR_HEIGHT, availableHeight / dimensionCount) ); // 使用调整后的条形高度 const finalBarHeight = adjustedBarHeight; const totalBarSpaceAdjusted = (finalBarHeight + barPadding) * dimensionCount; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ---------- // 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数
const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算)(便于其他模板复制复用) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
// 智能换行:优先按单词;利用率不足50%时尝试塞字母;长词断行加"-";断词后下一行单字母开头尽量回并 const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; };
// ---------- 5. 计算标签宽度 ----------
// 使用智能换行计算维度标签布局 const targetFontSize = parseFloat(typography.label.font_size) || 14; const maxLabelWidth_calc = 200; const maxLabelHeight = finalBarHeight; const lineSpacing = 1.2;
const dimLabelResult = buildDimLabelLayout({ containerSelector: containerSelector, labels: dimensions, fontConfig: typography.label, maxWidth: maxLabelWidth_calc, maxHeight: maxLabelHeight, lineSpacing: lineSpacing, targetFontSize: targetFontSize });
const dimLabelConfig = dimLabelResult.dimLabelConfig; const maxLabelWidth = dimLabelResult.maxLabelWidth;
// 根据标签宽度调整边距 margin.right = Math.max(margin.right, maxLabelWidth + 30); // ---------- 6. 创建比例尺 ---------- // 计算条形的额外间距(如果启用) const barScalePadding = variables.has_spacing ? 0.3 : 0.2; // 计算实际需要的总高度(基于调整后的条形高度) const actualNeededHeight = (finalBarHeight + barPadding) * dimensionCount; // 确保Y轴比例尺使用基于finalBarHeight计算的适当范围 // 如果actualNeededHeight小于innerHeight,则居中显示 const yAxisStart = Math.max(0, (innerHeight - actualNeededHeight) / 2); const yAxisEnd = Math.min(innerHeight, yAxisStart + actualNeededHeight); // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([yAxisStart, yAxisEnd]) .padding(barScalePadding); // X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添加5%边距 .range([0, innerWidth]);
// ---------- 7. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 添加渐变(如果启用) if (variables.has_gradient) { const primaryColor = colorResolver.other("primary", { fallback: "#882e2e" }).value; const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.3 })); } // ---------- 8. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 9. 绘制条形和标签 ---------- // 获取条形颜色的辅助函数 const getBarColor = () => { return colorResolver.other("primary", { fallback: "#882e2e" }).value; // 默认暗红色 }; // 绘制条形和标签 sortedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barBandHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]); const y = yScale(dimension); const centerY = y + barBandHeight / 2; // 创建条形组 const barGroup = g.append("g"); // 绘制矩形条形(没有圆角和边框) barGroup.append("rect") .attr("x", 0) .attr("y", y) .attr("width", barWidth) .attr("height", barBandHeight) .attr("fill", variables.has_gradient ? "url(#bar-gradient)" : getBarColor()) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); }); // 准备图标尺寸 const iconSize = barBandHeight * 0.7; const iconX = 0; const iconY = y + (barBandHeight - iconSize) / 2; // 添加图标(如果有)- 带白色圆形背景 if (images.field && images.field[dimension]) { // 添加白色圆形背景 barGroup.append("circle") .attr("cx", iconX + iconSize/2) .attr("cy", iconY + iconSize/2) .attr("r", iconSize/2) .attr("fill", "white"); // 添加图标 barGroup.append("image") .attr("x", iconX) .attr("y", iconY) .attr("width", iconSize) .attr("height", iconSize) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // 格式化数值用于显示 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; // 计算动态字体大小(条形高度的60%) const dynamicFontSize = `${barBandHeight * 0.6}px`; // 创建临时文本测量数值标签宽度(使用动态字体大小) const valueTextWidth = chartUtils.text.measure(svg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: dynamicFontSize, fontWeight: typography.annotation.font_weight }).width; // 判断数值标签是否能放入条形内 const labelFitsInside = valueTextWidth + 10 < barWidth; // 添加数值标签(使用动态字体大小) if (labelFitsInside) { // 标签放在条形内部 barGroup.append("text") .attr("x", barWidth - 5) .attr("y", y + barBandHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "end") .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", "#FFFFFF") // 白色 .text(formattedValue); } else { // 标签放在条形外部 barGroup.append("text") .attr("x", barWidth + 5) .attr("y", y + barBandHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) // 使用文本颜色 .text(formattedValue); }
// 添加维度标签(X标签)- 放在条形右边,支持多行换行 const labelConfig = dimLabelConfig[dimension]; const labelX = barWidth + (labelFitsInside ? 5 : valueTextWidth + 15); const labelGroup = barGroup.append("text") .attr("x", labelX) .attr("text-anchor", "start") .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
if (labelConfig.needsWrapping) { const lineHeight = labelConfig.lineHeight; const startY = centerY - ((labelConfig.lines.length - 1) * lineHeight) / 2; labelGroup.attr("y", startY);
labelConfig.lines.forEach((line, i) => { labelGroup.append("tspan") .attr("x", labelX) .attr("dy", i === 0 ? "0.35em" : `${lineHeight}`) .text(line); }); } else { labelGroup .attr("y", centerY) .attr("dy", "0.35em") .text(labelConfig.lines[0]); }
// 在第一个条形上显示单位(如果有) if (index === 0 && valueUnit) { barGroup.append("text") .attr("x", barWidth) .attr("y", y - 5) // 条形顶部上方 .attr("text-anchor", "end") .style("font-family", typography.annotation.font_family) .style("font-size", typography.annotation.font_size) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(`(${valueUnit})`); } } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_2_hand", "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[3, 20], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary", "secondary", "background"], "supported_effects": ["gradient", "opacity"], "min_height": 600, "min_width": 800, "background": "light", "icon_mark": "none", "icon_label": "none", "has_x_axis": "yes", "has_y_axis": "yes"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data; // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置,如果不存在则使用默认值 title: { font_family: "Arial", font_size: "18px", font_weight: "bold" }, label: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, description: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } }; const colors = jsonData.colors || { text_color: "#333333", other: { primary: "#D32F2F", // Red for "Still active" secondary: "#AAAAAA", // Gray for "Ended" background: "#F0F0F0" } }; // 颜色设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_shadow = variables.has_shadow || false; variables.has_stroke = variables.has_stroke || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 600; const height = variables.height || 400; // 设置边距 const margin = { top: 50, right: 30, bottom: 80, left: 40 }; // 计算实际绘图区域大小 const chartWidth = width - margin.left - margin.right; const chartHeight = height - margin.top - margin.bottom; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列获取字段名 const xField = chartUtils.schema.channel(jsonData, "x").key || "period"; const yField = chartUtils.schema.channel(jsonData, "y").key || "value"; // 获取字段单位(如果存在) let xUnit = ""; let yUnit = ""; let groupUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { xUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { yUnit = chartUtils.schema.channel(jsonData, "y").unit; }
// ---------- 4. 数据处理 ---------- // 处理数据,确保数据格式正确 const processedData = chartData.map(d => ({ category: d[xField], value: +d[yField] // 确保转换为数字 })); // ---------- 5. 创建比例尺 ---------- // Y轴比例尺 - 使用分类数据 const yScale = d3.scaleBand() .domain(processedData.map(d => d.category)) .range([0, chartHeight]) .padding(0.3); // X轴比例尺 - 使用数值 const xScale = d3.scaleLinear() .domain([0, d3.max(processedData, d => d.value)]) .range([0, chartWidth]) .nice();
const n_data = processedData.length // 颜色比例尺 const colorScale = (d, i) => { if (i === n_data - 1) { return colorResolver.variant(colorResolver.other("primary").value, { mode: "brighter", amount: 0.8 }); } return colorResolver.other("primary").value; };
// 确定标签的最大长度: let minYLabelRatio = 1.0 const maxYLabelWidth = yScale.bandwidth() * 1.03
chartData.forEach(d => { const yLabelText = String(d[xField]) let currentWidth = chartUtils.text.measure(null, yLabelText).width if (currentWidth > maxYLabelWidth) { minYLabelRatio = Math.min(minYLabelRatio, maxYLabelWidth / currentWidth) } })
// ---------- 6. 创建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"); // 添加图表主体容器 const chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 7. 绘制图表元素 ---------- // 添加X轴 const xAxis = d3.axisBottom(xScale) .ticks(5) .tickFormat(d => d + (yUnit ? ` ${yUnit}` : '')) .tickSize(0) // 移除刻度线 .tickPadding(10); // 增加文字和轴的间距 chartGroup.append("g") .attr("class", "x-axis") .attr("transform", `translate(0, ${chartHeight})`) .call(xAxis) .call(g => g.select(".domain").remove()) // 移除轴线 .selectAll("text") .remove(); // 添加Y轴 const yAxis = d3.axisLeft(yScale) .tickSize(0); // 移除刻度线 chartGroup.append("g") .attr("class", "y-axis") .call(yAxis) .selectAll("text") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("text-anchor", "end") .attr("dy", "0.32em") .attr("x", -10) .style("fill", colorResolver.text({ fallback: "#333333" }).value); // 添加条形 const bars = chartGroup.selectAll(".bar") .data(processedData) .enter() .append("rect") .attr("class", "bar") .attr("y", d => yScale(d.category)) .attr("x", 0) .attr("width", d => xScale(d.value)) .attr("height", yScale.bandwidth()) .attr("fill", (d, i) => colorScale(d, i)); // 添加数值标签 const labels = chartGroup.selectAll(".label") .data(processedData) .enter() .append("text") .attr("class", "label") .attr("x", d => xScale(d.value) + 5) .attr("y", d => yScale(d.category) + yScale.bandwidth() / 2) .attr("dy", "0.32em") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(d => chartUtils.format.number(d.value, { unit: yUnit, spaceBeforeUnit: true }).text) .style("opacity", 1); // 直接设置为可见
const roughness = 1; const bowing = 2; const fillStyle = "hachure"; const randomize = false; const pencilFilter = false; const svgConverter = new svg2roughjs.Svg2Roughjs(containerSelector); svgConverter.pencilFilter = pencilFilter; svgConverter.randomize = randomize; svgConverter.svg = svg.node(); svgConverter.roughConfig = { bowing, roughness, fillStyle }; svgConverter.sketch(); // Remove the first SVG element if it exists const firstSvg = document.querySelector(`${containerSelector} svg`); if (firstSvg) { firstSvg.remove(); } return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_3", "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[3, 20], [0, 100]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary", "secondary", "background"], "supported_effects": ["gradient", "opacity"], "min_height": 600, "min_width": 800, "background": "light", "icon_mark": "none", "icon_label": "none", "has_x_axis": "yes", "has_y_axis": "yes"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data; // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置,如果不存在则使用默认值 title: { font_family: "Arial", font_size: "18px", font_weight: "bold" }, label: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, description: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } }; const colors = jsonData.colors || { text_color: "#333333", other: { primary: "#D32F2F", // Red for "Still active" secondary: "#AAAAAA", // Gray for "Ended" background: "#F0F0F0" } }; // 颜色设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 数值单位规范 // 添加数值格式化函数 // 设置视觉效果变量的默认值 variables.has_shadow = variables.has_shadow || false; variables.has_stroke = variables.has_stroke || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 600; const height = variables.height || 400; // 设置边距 const margin = { top: 50, right: 30, bottom: 80, left: 40 }; // 计算实际绘图区域大小 const chartWidth = width - margin.left - margin.right; const chartHeight = height - margin.top - margin.bottom; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列获取字段名 const xField = chartUtils.schema.channel(jsonData, "x").key || "period"; const yField = chartUtils.schema.channel(jsonData, "y").key || "value"; // 获取字段单位(如果存在) let xUnit = ""; let yUnit = ""; let groupUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { xUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { yUnit = chartUtils.schema.channel(jsonData, "y").unit; }
// ---------- 4. 数据处理 ---------- // 处理数据,确保数据格式正确 const processedData = chartData.map(d => ({ category: d[xField], value: +d[yField] // 确保转换为数字 })).sort((a, b) => b.value - a.value); // 按值降序排序 // ---------- 5. 创建比例尺 ---------- // Y轴比例尺 - 使用分类数据 const yScale = d3.scaleBand() .domain(processedData.map(d => d.category)) .range([0, chartHeight]) .padding(0.3); // X轴比例尺 - 使用数值 const xScale = d3.scaleLinear() .domain([0, d3.max(processedData, d => d.value)]) .range([0, chartWidth]) .nice();
// 颜色比例尺 const colorScale = d3.scaleLinear() .domain([0, processedData.length - 1]) .range([colorResolver.other("primary").value, d3.interpolateRgb(colorResolver.other("primary").value, "#ffffff")(0.6)]);
// ---------- 6. 创建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"); // 添加图表主体容器 const chartGroup = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 7. 绘制图表元素 ---------- // 添加X轴(隐藏) const xAxis = d3.axisBottom(xScale) .ticks(5) .tickFormat(d => chartUtils.format.autoText(d) + (yUnit ? ` ${yUnit}` : '')) .tickSize(0) // 移除刻度线 .tickPadding(10); // 增加文字和轴的间距 chartGroup.append("g") .attr("class", "x-axis") .attr("transform", `translate(0, ${chartHeight})`) .call(xAxis) .call(g => g.select(".domain").remove()) // 移除轴线 .selectAll("text") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("opacity", 0); // 隐藏X轴文本 // 添加Y轴(不显示刻度线) const yAxis = d3.axisLeft(yScale) .tickSize(0); // 移除刻度线
const yAxisGroup = chartGroup.append("g") .attr("class", "y-axis") .call(yAxis) yAxisGroup.selectAll("text") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
let iconSize = yScale.bandwidth()*0.7 let iconPadding = 10 yAxisGroup.selectAll(".tick").each(function(d) { const tick = d3.select(this); if(jsonData.images && jsonData.images.field[d]) { tick.append("image") .attr("x", - iconSize - iconPadding) // 10是原有的padding .attr("y", -iconSize/2) .attr("width", iconSize) .attr("height", iconSize) .attr("xlink:href", jsonData.images.field[d]); tick.select("text") .style("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .attr("x", -iconSize-2*iconPadding) } }); // 添加条形 const bars = chartGroup.selectAll(".bar") .data(processedData) .enter() .append("rect") .attr("class", "bar") .attr("y", d => yScale(d.category)) .attr("x", 0) .attr("height", yScale.bandwidth()) .attr("width", d => xScale(d.value)) // 直接设置最终宽度 .attr("fill", (d, i) => colorScale(i)); // 添加数值标签 const labels = chartGroup.selectAll(".label") .data(processedData) .enter() .append("text") .attr("class", "label") .attr("y", d => yScale(d.category) + yScale.bandwidth() / 2) .attr("x", d => xScale(d.value) + 5) .attr("dy", ".35em") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(d => chartUtils.format.autoText(d.value) + (yUnit ? ` ${yUnit}` : '')) .style("opacity", 1); // 直接设置为可见
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_30", "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": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "gradient", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.jsfunction makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; // 提取维度字段 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; // 获取数据维度数量 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; const dimensionCount = dimensions.length; // 设置边距 const margin = { top: 90, // 顶部留出标题空间 right: 120, // 右侧足够显示标签 bottom: 60, // 底部边距 left: 100 // 左侧空间 }; // 计算每个条形的理想高度 - 减小最小和最大高度 const MIN_BAR_HEIGHT = 36; // 从64减小到45 const MAX_BAR_HEIGHT = 72; // 从128减小到90 const barPadding = variables.has_spacing ? 20 : 10; // 计算内部绘图区域尺寸(暂时宽度) const innerWidth = width - margin.left - margin.right; let innerHeight; // 高度稍后初始化 // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ---------- // 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]);
// 添加数值格式化函数
// 计算最大值和最小值用于条形高度的缩放 const maxValue = d3.max(chartData, d => +d[valueField]); const minValue = d3.min(chartData, d => +d[valueField]); // ---------- 5. 计算标签宽度 ---------- // 创建临时SVG来测量文本宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden"); // 计算最大数值标签宽度 let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`; const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width; maxValueWidth = Math.max(maxValueWidth, textWidth); }); // 计算最大维度标签宽度 let maxLabelWidth = 0; dimensions.forEach(dimension => { // 格式化维度名称(附加单位,如果有) const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; const textWidth = chartUtils.text.measure(tempSvg, formattedDimension, { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }).width; maxLabelWidth = Math.max(maxLabelWidth, textWidth); }); // 删除临时SVG tempSvg.remove(); // 根据标签宽度调整边距 margin.right = Math.max(margin.right, maxLabelWidth + 30); // ---------- 6. 创建比例尺 ---------- // 固定条形间距 const fixedBarSpacing = 15; // 条形之间的固定间距像素值 // 创建条形高度比例尺 - 根据数值大小来变化条形高度(1-2倍基础高度) const barHeightScale = d3.scaleLinear() .domain([minValue, maxValue]) .range([1, 2]); // 1倍到2倍的倍数范围 // 基础条形高度 - 减小默认值 const baseBarHeight = Math.min(MAX_BAR_HEIGHT, Math.max(MIN_BAR_HEIGHT, 50)); // 从60减小到50 // 计算每个条形的高度 const barHeights = sortedDimensions.map(dimension => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const heightScale = barHeightScale(+dataPoint[valueField]); return baseBarHeight * heightScale; } return baseBarHeight; }); // 计算总高度需求,包含固定间距 const totalBarSpaceNeeded = barHeights.reduce((sum, height) => sum + height, 0) + (barHeights.length - 1) * fixedBarSpacing; // 计算图表所需的最小高度 const extraSpace = 150; // 为标题和底部空间预留的额外高度 const minHeight = variables.min_height || 400; const calculatedHeight = Math.max(minHeight, totalBarSpaceNeeded + extraSpace); // 使用计算值或用户指定值作为最终高度 const height = variables.height || calculatedHeight; // 更新内部高度 innerHeight = height - margin.top - margin.bottom; // X轴比例尺(用于数值)- 最小宽度从50改为100 const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添加5%边距 .range([75, innerWidth]); // 从100开始,而不是50
// ---------- 7. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 添加渐变(如果启用) if (variables.has_gradient) { const primaryColor = colorResolver.other("primary", { fallback: "#882e2e" }).value; const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.3 })); } // ---------- 8. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 9. 绘制条形和标签 ---------- // 获取条形颜色的辅助函数 const getBarColor = () => { return colorResolver.other("primary", { fallback: "#882e2e" }).value; // 默认暗红色 }; // 计算所有条形中的最小高度,用于统一圆圈大小 let minBarHeight = Math.min(...barHeights); const uniformCircleRadius = minBarHeight * 0.3; // 计算每个条形的Y坐标,使用固定间距 let barPositions = []; let currentY = 0; barHeights.forEach(height => { barPositions.push(currentY); currentY += height + fixedBarSpacing; }); // 居中调整所有条形 const totalUsedHeight = currentY - fixedBarSpacing; // 减去最后一个不需要的间距 const startY = (innerHeight - totalUsedHeight) / 2; // 绘制条形和标签 sortedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { // 计算实际条形高度 const barBandHeight = barHeights[index]; // 使用预先计算的Y位置,加上居中调整 const y = startY + barPositions[index]; const barWidth = xScale(+dataPoint[valueField]); const centerY = y + barBandHeight / 2; // 创建条形组 const barGroup = g.append("g"); // 绘制矩形条形(没有圆角和边框) barGroup.append("rect") .attr("x", 0) .attr("y", y) .attr("width", barWidth) .attr("height", barBandHeight) .attr("fill", variables.has_gradient ? "url(#bar-gradient)" : getBarColor()) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); }); // 准备图标尺寸 const iconSize = barBandHeight * 0.7; const iconX = 10; const iconY = y + (barBandHeight - iconSize) / 2; // 添加图标(如果有)- 带白色圆形背景 if (images.field && images.field[dimension]) { // 添加白色圆形背景 barGroup.append("circle") .attr("cx", iconX + iconSize/2) .attr("cy", iconY + iconSize/2) .attr("r", iconSize/2) .attr("fill", "white"); // 添加图标 barGroup.append("image") .attr("x", iconX) .attr("y", iconY) .attr("width", iconSize) .attr("height", iconSize) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // 格式化数值用于显示 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; // 减小字体大小(条形高度的比例) const valueFontSize = `${barBandHeight * 0.35}px`; const labelFontSize = `${barBandHeight * 0.22}px`; // 明显更小的x标签字体大小 // 创建临时文本测量数值标签宽度 const valueTextWidth = chartUtils.text.measure(svg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: valueFontSize, fontWeight: typography.annotation.font_weight }).width; // 判断数值标签是否能放入条形内 const labelFitsInside = valueTextWidth + 40 < barWidth; // 增加边距以容纳两行 // 添加标签 - 两行:数值和维度名称 if (labelFitsInside) { // 标签放在条形内部 // 第一行:数值(上面一行) barGroup.append("text") .attr("x", barWidth - 15) .attr("y", centerY - barBandHeight * 0.15) .attr("text-anchor", "end") .style("font-family", typography.annotation.font_family) .style("font-size", valueFontSize) .style("font-weight", "bold") .style("fill", "#FFFFFF") // 白色 .text(formattedValue); // 第二行:维度名称(下面一行)- 使用更小的字体 barGroup.append("text") .attr("x", barWidth - 15) .attr("y", centerY + barBandHeight * 0.15) .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", labelFontSize) .style("font-weight", "normal") .style("fill", "#FFFFFF") // 白色 .text(dimension); } else { // 标签放在条形内左侧 barGroup.append("text") .attr("x", 15) .attr("y", centerY) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", valueFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", "#FFFFFF") // 白色 .text(formattedValue); } // 添加排名圆圈(黑色圆圈,白色文字)- 使用统一的半径 const rankingCirclePadding = 5; // 圆圈与条形之间的间距 const rankingCircleX = barWidth + rankingCirclePadding + uniformCircleRadius; // 绘制黑色圆圈 barGroup.append("circle") .attr("cx", rankingCircleX) .attr("cy", centerY) .attr("r", uniformCircleRadius) .attr("fill", "#000000"); // 黑色填充 // 添加排名数字(白色) barGroup.append("text") .attr("x", rankingCircleX) .attr("y", centerY) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "middle") // 水平居中 .style("font-family", typography.annotation.font_family) .style("font-size", `${uniformCircleRadius * 1.2}px`) // 字体大小适合圆圈 .style("font-weight", "bold") .style("fill", "#FFFFFF") // 白色 .text(index + 1); // 排名从1开始 // 在第一个条形上显示单位(如果有) if (index === 0 && valueUnit) { barGroup.append("text") .attr("x", barWidth) .attr("y", y - 5) // 条形顶部上方 .attr("text-anchor", "end") .style("font-family", typography.annotation.font_family) .style("font-size", typography.annotation.font_size) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(`(${valueUnit})`); } } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_33", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 600, "background": "none", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.js Horizontal Bar Chart plain chart#3 bar顶端三角function makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data; // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 60, // 顶部留出标题空间 right: 60, // 右侧足够显示数值 bottom: 30, // 底部边距 left: 150 // 左侧初始空间,用于维度标签和图标 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionChannel = chartUtils.schema.column(dataColumns, 0, { fallbackKey: "dimension" }); const valueChannel = chartUtils.schema.column(dataColumns, 1, { fallbackKey: "value" }); const dimensionField = dimensionChannel.key; const valueField = valueChannel.key; const dimensionUnit = dimensionChannel.unit; const valueUnit = valueChannel.unit; // ---------- 4. 数据处理 ---------- // 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 如果x维度数量超过15,每增加一个x,整个图像的高度增加3% const baseHeight = variables.height || 600; const adjustedHeight = dimensions.length > 15 ? baseHeight * (1 + (dimensions.length - 15) * 0.03) : baseHeight; // 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数
// 计算图标尺寸 const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
// 智能换行:优先按单词;利用率不足50%时尝试塞字母;长词断行加"-";断词后下一行单字母开头尽量回并 const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; };
// ---------- 5. 计算标签宽度和布局 ----------
// 计算内部尺寸(先计算innerHeight,yScale依赖它) const innerHeight = height - margin.top - margin.bottom;
// 计算条形的额外间距(如果启用) const barPadding = variables.has_spacing ? 0.3 : 0.2;
// Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
const barHeight = yScale.bandwidth(); const barGap = Math.max(0, yScale.step() - yScale.bandwidth());
// 图标尺寸配置 const defaultFlagWidth = 48; const defaultFlagHeight = 48; const flagPadding = 0; const textPadding = 5;
// 计算动态图标尺寸 const iconSize = calcIconSize(barHeight, { maxSize: 30, minRatio: 0.8, minPx: 10 }); let flagWidth = iconSize.width; let flagHeight = iconSize.height;
// 构造带单位的标签列表 const dimLabelsWithUnit = sortedDimensions.map(dimension => dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}` );
// 智能换行布局计算 const dimLabelMaxWidth = width * 0.2; const maxDimLabelHeight = barHeight + barGap; const dimLabelLineSpacing = 1.01;
const dimLabelLayout = buildDimLabelLayout({ containerSelector: containerSelector, labels: dimLabelsWithUnit, fontConfig: typography.label, maxWidth: dimLabelMaxWidth, maxHeight: maxDimLabelHeight, lineSpacing: dimLabelLineSpacing, targetFontSize: Math.min(20, barHeight * 0.6) });
const dimLabelConfig = dimLabelLayout.dimLabelConfig; const maxDimLabelWidth = dimLabelLayout.maxLabelWidth;
// 计算最大数值标签宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`;
const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width; maxValueWidth = Math.max(maxValueWidth, textWidth); });
tempSvg.remove();
// 更新左边距(图标+标签宽度+间距) const requiredLeftSpace = maxDimLabelWidth + textPadding + flagWidth + textPadding; margin.left = requiredLeftSpace + 5; margin.right = Math.max(margin.right, maxValueWidth + 20);
// 计算内部绘图��域尺寸 const innerWidth = width - margin.left - margin.right; // ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 添加渐变(如果启用) if (variables.has_gradient) { const primaryColor = colorResolver.other("primary", { fallback: "#882e2e" }).value; const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.3 })); }
// ---------- 7. 创建X轴比例尺 ----------
// X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添加5%边距 .range([0, innerWidth]);
// ---------- 8. 添加标题和副标题 ---------- // 添加标题(如果有) if (variables.title && variables.title.text) { svg.append("text") .attr("x", margin.left) .attr("y", margin.top / 2) .attr("text-anchor", "start") .style("font-family", typography.title.font_family) .style("font-size", typography.title.font_size) .style("font-weight", typography.title.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(variables.title.text); } // 添加副标题(如果有) if (variables.subtitle && variables.subtitle.text) { svg.append("text") .attr("x", margin.left) .attr("y", margin.top / 2 + 20) .attr("text-anchor", "start") .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(variables.subtitle.text); } // ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制条形和标签 ---------- // 获取条形颜色的辅助函数 // 获取条形颜色的辅助函数 const getBarColor = () => { return colorResolver.other("primary", { fallback: "#882e2e" }).value; // 默认暗红色 };
// 获取描边颜色的辅助函数 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.available(0, { fallback: "#333333" }).value; }; // 添加交替行背景(如果需要) if (jsonData.variation?.background === "styled") { sortedDimensions.forEach((dimension, i) => { if (i % 2 === 0) { g.append("rect") .attr("x", -margin.left/2) .attr("y", yScale(dimension)) .attr("width", innerWidth + margin.left/2 + margin.right/2) .attr("height", yScale.bandwidth()) .attr("class","background") .attr("fill", colorResolver.background({ fallback: "#f5f5f5" }).value) .attr("opacity", 0.8); } }); } // 为每个维度绘制条形和标签 sortedDimensions.forEach(dimension => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]); // 绘制带三角形尾部的条形 if (barWidth > 0) { // 仅当宽度大于0时绘制 // 三角形的宽度,设置为条形图高度,但最小10px,最大30px const triangleWidth = Math.min(30, Math.max(10, barHeight)); // 确保三角形宽度不超过总宽度 const actualTriangleWidth = Math.min(triangleWidth, barWidth); // 矩形部分的宽度 const rectWidth = barWidth - actualTriangleWidth;
g.append("path") .attr("d", () => { const yPos = yScale(dimension); // 构建路径 // 从左上角开始 let path = `M 0 ${yPos}`; // 到矩形右上角 path += ` L ${rectWidth} ${yPos}`; // 到三角形上顶点 path += ` L ${rectWidth} ${yPos}`; // 到三角形右侧顶点 (尖端) path += ` L ${barWidth} ${yPos + barHeight / 2}`; // 到三角形下顶点 path += ` L ${rectWidth} ${yPos + barHeight}`; // 到矩形右下角 path += ` L ${rectWidth} ${yPos + barHeight}`; // 到左下角 path += ` L 0 ${yPos + barHeight}`; // 闭合路径 path += ` Z`; return path; }) .attr("fill", variables.has_gradient ? "url(#bar-gradient)" : getBarColor()) .style("stroke", variables.has_stroke ? getStrokeColor() : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); }); } // 添加带图标的维度标签 const flagX = -flagWidth - flagPadding - 5; const labelY = yScale(dimension) + barHeight / 2; // 添加图标(如果有) if (images.field && images.field[dimension]) { g.append("image") .attr("x", flagX) .attr("y", labelY - flagHeight / 2) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // 添加维度标签 g.append("text") .attr("x", flagX - 5) .attr("y", labelY) .attr("dy", "0.35em") .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension); // 添加数值标签 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; g.append("text") .attr("x", barWidth + 5) .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_4", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.jsfunction makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 数值单位规范 // 添加数值格式化函数
// 根据条形高度计算icon尺寸 const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; };
// ���置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 60, // 顶部留出标题空间 right: 60, // 右侧足够显示数值 bottom: 30, // 底部边距 left: 150 // 左侧初始空间,用于维度标签和图标 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; // 默认为百分比 if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ----------
// 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))];
// 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]);
// ---------- 5. 布局设置 ----------
// 图标尺寸 const flagWidth = 20; const flagHeight = 15; const flagPadding = 0;
// 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom;
// ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 添加渐变(如果启用) if (variables.has_gradient) { const primaryColor = colorResolver.other("primary", { fallback: "#882e2e" }).value; const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.3 })); } // ---------- 7. 创建比例尺 ---------- // 计算条形的额外间距(如果启用) const barPadding = variables.has_spacing ? 0.3 : 0.2; // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添加5%边距 .range([0, innerWidth]);
// ---------- 8. 计算维度标签布局(智能换行)----------
const barHeight = yScale.bandwidth(); const barGap = Math.max(0, yScale.step() - yScale.bandwidth()); const maxDimLabelHeight = barHeight + barGap;
const dimLabelLayout = buildDimLabelLayout({ containerSelector: containerSelector, labels: sortedDimensions, fontConfig: typography.label, maxWidth: Math.max(100, margin.left - flagWidth - 20), maxHeight: maxDimLabelHeight * 0.8, lineSpacing: 1.01, targetFontSize: Math.min(20, barHeight * 0.6) }); const dimLabelConfig = dimLabelLayout.dimLabelConfig;
// 根据实际标签宽度调整左边距 margin.left = Math.max(margin.left, dimLabelLayout.maxLabelWidth + flagWidth + 30);
// ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制条形和标签 ---------- // 获取条形颜色的辅助函数 // 获取条形颜色的辅助函数 const getBarColor = () => { return colorResolver.other("primary", { fallback: "#882e2e" }).value; // 默认暗红色 };
// 获取描边颜色的辅助函数 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.available(0, { fallback: "#333333" }).value; }; // 添加交替行背景(如果需要) if (jsonData.variation?.background === "styled") { sortedDimensions.forEach((dimension, i) => { if (i % 2 === 0) { g.append("rect") .attr("x", -margin.left/2) .attr("y", yScale(dimension)) .attr("width", innerWidth + margin.left/2 + margin.right/2) .attr("height", yScale.bandwidth()) .attr("class","background") .attr("fill", colorResolver.background({ fallback: "#f5f5f5" }).value) .attr("opacity", 0.8); } }); } // 为每个维度绘制条形和标签 sortedDimensions.forEach(dimension => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]); // 绘制条形 g.append("rect") .attr("x", 0) .attr("y", yScale(dimension)) .attr("width", barWidth) .attr("height", barHeight) .attr("fill", variables.has_gradient ? "url(#bar-gradient)" : getBarColor()) .attr("rx", variables.has_rounded_corners ? 3 : 0) .attr("ry", variables.has_rounded_corners ? 3 : 0) .style("stroke", variables.has_stroke ? getStrokeColor() : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); }); // 添加带图标的维度标签 const flagX = -flagWidth - flagPadding - 5; const labelY = yScale(dimension) + barHeight / 2; // 添加图标(如果有) if (images.field && images.field[dimension]) { g.append("image") .attr("x", flagX) .attr("y", labelY - flagHeight / 2) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // 添加维度标签(支持多行智能换行) const labelConfig = dimLabelConfig[dimension]; const textElem = g.append("text") .attr("x", flagX - 5) .attr("y", labelY) .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
if (labelConfig.needsWrapping) { const lineHeight = labelConfig.lineHeight; const startY = labelY - (labelConfig.lines.length - 1) * lineHeight / 2; textElem.attr("y", startY); labelConfig.lines.forEach((line, i) => { textElem.append("tspan") .attr("x", flagX - 5) .attr("dy", i === 0 ? "0.35em" : `${lineHeight}px`) .text(line); }); } else { textElem.attr("dy", "0.35em") .text(labelConfig.lines[0] || dimension); } // 添加数值标签 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; g.append("text") .attr("x", barWidth + 5) .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_4_hand", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.jsfunction makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 数值单位规范 // 添加数值格式化函数
// 根据条形高度计算icon尺寸 const calcIconSize = (barHeight, options = {}) => { const maxSize = typeof options.maxSize === "number" ? options.maxSize : 30; const minRatio = typeof options.minRatio === "number" ? options.minRatio : 0.8; const minPx = typeof options.minPx === "number" ? options.minPx : 10; const size = Math.min(maxSize, Math.max(barHeight * minRatio, minPx)); return { width: size, height: size }; };
// 计算类别label布局(统一字号+智能换行+测宽+margin.left计算) const buildDimLabelLayout = (params) => { const { containerSelector, labels, fontConfig, maxWidth, maxHeight, lineSpacing, targetFontSize } = params;
const tempMeasureSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
const measureWidth = (text, fontSize) => chartUtils.text.measure(tempMeasureSvg, text, { fontFamily: fontConfig.font_family, fontSize, fontWeight: fontConfig.font_weight }).width;
const breakLongWord = (word, maxWidth, fontSize) => { const lines = []; let currentLine = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testWithChar = currentLine + char; const testWithHyphen = currentLine + "-"; if (measureWidth(testWithChar, fontSize) > maxWidth && currentLine !== "") { lines.push(testWithHyphen); currentLine = char; } else { currentLine = testWithChar; } } if (currentLine !== "") lines.push(currentLine); return lines.length > 0 ? lines : [word]; };
const breakWordIntoCurrentLine = (currentLine, word, maxWidth, fontSize) => { const completedLines = []; let chars = ""; for (let i = 0; i < word.length; i++) { const char = word[i]; const testLine = currentLine + chars + char; const testLineWithHyphen = currentLine + chars + "-"; if (measureWidth(testLine, fontSize) > maxWidth) { if (chars === "") { completedLines.push(currentLine); const brokenLines = breakLongWord(word, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } completedLines.push(testLineWithHyphen); const remaining = word.substring(i); const remainingWidth = measureWidth(remaining, fontSize); if (remainingWidth > maxWidth) { const brokenLines = breakLongWord(remaining, maxWidth, fontSize); return { completedLines: [...completedLines, ...brokenLines.slice(0, -1)], remaining: brokenLines[brokenLines.length - 1] }; } return { completedLines, remaining }; } chars += char; } return { completedLines, remaining: currentLine + chars }; };
const wrapSmart = (text, maxWidth, fontSize) => { const words = String(text || "").split(/\s+/).filter(w => w !== ""); if (words.length === 0) return [String(text || "")];
const lines = []; let currentLine = "";
for (let i = 0; i < words.length; i++) { const word = words[i]; const separator = currentLine === "" ? "" : " "; const testLine = currentLine + separator + word; if (measureWidth(testLine, fontSize) <= maxWidth) { currentLine = testLine; continue; }
if (currentLine === "") { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; continue; }
const utilization = measureWidth(currentLine, fontSize) / maxWidth; if (utilization < 0.5) { const result = breakWordIntoCurrentLine(currentLine, word, maxWidth, fontSize); lines.push(...result.completedLines); currentLine = result.remaining; continue; }
lines.push(currentLine); if (measureWidth(word, fontSize) > maxWidth) { const broken = breakLongWord(word, maxWidth, fontSize); lines.push(...broken.slice(0, -1)); currentLine = broken[broken.length - 1]; } else { currentLine = word; } }
if (currentLine !== "") lines.push(currentLine);
const out = [...lines]; for (let i = 1; i < out.length; i++) { const prevTrim = (out[i - 1] || "").trimEnd(); if (!prevTrim.endsWith("-")) continue;
const curTrim = String(out[i] || "").trim(); const match = curTrim.match(/^([A-Za-z])(\s+.*)?$/); if (!match) continue;
const firstLetter = match[1]; const rest = (match[2] || "").trimStart(); const candidatePrev = prevTrim.slice(0, -1) + firstLetter; if (measureWidth(candidatePrev, fontSize) > maxWidth) continue;
out[i - 1] = candidatePrev; if (rest === "") { out.splice(i, 1); i -= 1; } else { out[i] = rest; } }
return out.length > 0 ? out : [String(text || "")]; };
const fitsAll = (fontSize) => { const lineHeight = fontSize * lineSpacing; for (let i = 0; i < labels.length; i++) { const labelText = String(labels[i] || ""); const lines = wrapSmart(labelText, maxWidth, fontSize); const totalHeight = (lines.length <= 1) ? fontSize : ((lines.length - 1) * lineHeight + fontSize); if (totalHeight > maxHeight) return false; } return true; };
let low = 1; let high = targetFontSize; for (let i = 0; i < 18; i++) { const mid = (low + high) / 2; if (fitsAll(mid)) low = mid; else high = mid; }
const bestFontSize = low; const lineHeight = bestFontSize * lineSpacing; const dimLabelConfig = {}; let maxLabelWidth = 0;
for (let i = 0; i < labels.length; i++) { const label = labels[i]; const labelText = String(label || ""); const lines = wrapSmart(labelText, maxWidth, bestFontSize); dimLabelConfig[label] = { fontSize: bestFontSize, lineHeight: lineHeight, lines: lines, needsWrapping: lines.length > 1 }; for (let j = 0; j < lines.length; j++) { maxLabelWidth = Math.max(maxLabelWidth, measureWidth(lines[j], bestFontSize)); } }
tempMeasureSvg.remove(); return { dimLabelConfig, maxLabelWidth, fontSize: bestFontSize, lineHeight }; };
// 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 const margin = { top: 60, // 顶部留出标题空间 right: 60, // 右侧足够显示数值 bottom: 30, // 底部边距 left: 150 // 左侧初始空间,用于维度标签和图标 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; // 默认为百分比 if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ---------- // 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]);
// ---------- 5. 布局计算和字体调整 ----------
const textPadding = 5; const maxIconSize = 30; const dimLabelMaxWidth = width * 0.25; const dimLabelLineSpacing = 1.01; const targetLabelFontSize = parseFloat(typography.label.font_size) || 12; const textIconGap = 5; const flagBarGap = 10; const barValueGap = 10;
// 计算内部绘图区域尺寸(初始值) let innerWidth = width - margin.left - margin.right; let innerHeight = height - margin.top - margin.bottom;
// Y轴比例尺(用于维度) const barPadding = variables.has_spacing ? 0.3 : 0.2; const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding);
const rowHeight = yScale.bandwidth();
// icon尺寸(按rowHeight动态) const iconSize = calcIconSize(rowHeight, { maxSize: maxIconSize, minRatio: 0.8, minPx: 10 }); const flagWidth = iconSize.width; const flagHeight = iconSize.height;
// 调用智能换行布局计算 const dimLabelResult = buildDimLabelLayout({ containerSelector: containerSelector, labels: sortedDimensions, fontConfig: typography.label, maxWidth: dimLabelMaxWidth, maxHeight: rowHeight, lineSpacing: dimLabelLineSpacing, targetFontSize: targetLabelFontSize });
const { dimLabelConfig, maxLabelWidth } = dimLabelResult;
// 计算最大数值标签宽度(用于右边距) const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden");
let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`;
const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width; maxValueWidth = Math.max(maxValueWidth, textWidth); });
tempSvg.remove();
// 根据标签宽度调整左边距 margin.left = maxLabelWidth + textIconGap + flagWidth + flagBarGap;
// 调整右边距以适应数值标签 margin.right = Math.max(margin.right, maxValueWidth + barValueGap);
// 重新计算内部绘图区域尺寸 innerWidth = width - margin.left - margin.right; innerHeight = height - margin.top - margin.bottom; // ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 添加渐变(如果启用) if (variables.has_gradient) { const primaryColor = colorResolver.other("primary", { fallback: "#882e2e" }).value; const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "darker", amount: 0.3 })); } // ---------- 7. 创建比例尺 ----------
// X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添加5%边距 .range([0, innerWidth]);
// ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制条形和标签 ---------- // 获取条形颜色的辅助函数 // 获取条形颜色的辅助函数 const getBarColor = () => { return colorResolver.other("primary", { fallback: "#882e2e" }).value; // 默认暗红色 };
// 获取描边颜色的辅助函数 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.available(0, { fallback: "#333333" }).value; }; // 添加交替行背景(如果需要) if (jsonData.variation?.background === "styled") { sortedDimensions.forEach((dimension, i) => { if (i % 2 === 0) { g.append("rect") .attr("x", -margin.left/2) .attr("y", yScale(dimension)) .attr("width", innerWidth + margin.left/2 + margin.right/2) .attr("height", yScale.bandwidth()) .attr("class","background") .attr("fill", colorResolver.background({ fallback: "#f5f5f5" }).value) .attr("opacity", 0.8); } }); } // 为每个维度绘制条形和标签 sortedDimensions.forEach(dimension => { const dataPoint = chartData.find(d => d[dimensionField] === dimension);
if (dataPoint) { const barHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]); const centerY = yScale(dimension) + barHeight / 2;
// 绘制条形 g.append("rect") .attr("x", 0) .attr("y", yScale(dimension)) .attr("width", barWidth) .attr("height", barHeight) .attr("fill", variables.has_gradient ? "url(#bar-gradient)" : getBarColor()) .attr("rx", variables.has_rounded_corners ? 3 : 0) .attr("ry", variables.has_rounded_corners ? 3 : 0) .style("stroke", variables.has_stroke ? getStrokeColor() : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); });
// 计算文本X位置和图标位置 const textX = -textIconGap - flagWidth - textIconGap; const flagX = -flagWidth - textIconGap;
// 添加维度文本标签(支持多行) const labelConfig = dimLabelConfig[dimension]; const labelGroup = g.append("text") .attr("x", textX) .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", `${labelConfig.fontSize}px`) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value);
if (labelConfig.needsWrapping) { const lineHeight = labelConfig.lineHeight; const startY = centerY - ((labelConfig.lines.length - 1) * lineHeight) / 2; labelGroup.attr("y", startY);
labelConfig.lines.forEach((line, i) => { labelGroup.append("tspan") .attr("x", textX) .attr("dy", i === 0 ? "0.35em" : `${lineHeight}`) .text(line); }); } else { labelGroup .attr("y", centerY) .attr("dy", "0.35em") .text(labelConfig.lines[0]); }
// 添加图标(如果有) if (images.field && images.field[dimension]) { g.append("image") .attr("x", flagX) .attr("y", centerY - flagHeight / 2) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xlink:href", images.field[dimension]); }
// 添加数值标签 const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`;
g.append("text") .attr("x", barWidth + barValueGap) .attr("y", centerY) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(20, Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue); } }); const roughness = 1; const bowing = 2; const fillStyle = "hachure"; const randomize = false; const pencilFilter = false; const svgConverter = new svg2roughjs.Svg2Roughjs(containerSelector); svgConverter.pencilFilter = pencilFilter; svgConverter.randomize = randomize; svgConverter.svg = svg.node(); svgConverter.roughConfig = { bowing, roughness, fillStyle }; svgConverter.sketch(); // Remove the first SVG element if it exists const firstSvg = document.querySelector(`${containerSelector} svg`); if (firstSvg) { firstSvg.remove(); } // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384/* REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_5", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.js (样式02)function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333", other: { primary: "#0099ff" } // 默认使用蓝色作为条形颜色 }; const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 数值单位规范 // 添加数值格式化函数 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const originalHeight = variables.height || 600; // 设置边距 - 这个样式需要更多的上部和下部空间用于标签 const margin = { top: 100, // 顶部边距 right: 80, // 右侧足够显示数值标签 bottom: 70, // 底部边距 left: 20 // 左侧边距 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; // 默认为百分比 if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ---------- // 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 按数值降序排序数据(与图片相符) const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // ---------- 5. 计算标签宽度、动态高度和图表尺寸 ---------- // 动态调整高度 const numDimensions = sortedDimensions.length; let adjustedHeight = originalHeight; const maxHeightFactor = 1.88; if (numDimensions > 18) { // 根据条目数量比例计算建议高度 const suggestedHeight = originalHeight * (numDimensions / 18); // 限制最大高度 adjustedHeight = Math.min(suggestedHeight, originalHeight * maxHeightFactor); } // 使用调整后的高度 const height = adjustedHeight; // 创建临时SVG来测量文本宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden"); // 计算最大维度标签宽度 let maxLabelWidth = 0; dimensions.forEach(dimension => { // 格式化维度名称(附加单位,如果有) const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; const textWidth = chartUtils.text.measure(tempSvg, formattedDimension, { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }).width; maxLabelWidth = Math.max(maxLabelWidth, textWidth); }); // 计算最大数值标签宽度 let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`; const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width; maxValueWidth = Math.max(maxValueWidth, textWidth); }); // 删除临时SVG tempSvg.remove(); // 根据标签宽度调整右边距 margin.right = Math.max(margin.right, maxValueWidth + 10); // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 添加渐变(如果启用) if (variables.has_gradient) { const primaryColor = colorResolver.other("primary", { fallback: "#0099ff" }).value; const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", d3.rgb(primaryColor)); } // ---------- 7. 创建比例尺 ---------- // 计算条形的额外间距(如果启用) const barPadding = variables.has_spacing ? 0.7 : 0.6 ; // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.1]) // 添加10%边距 .range([0, innerWidth]); // ---------- 4. 在"正式渲染"前,测量合适的维度标签字体大小 ----------
// 4.1 从 typography.label.font_size 中解析初始字号(可能是 "12px" 这种写法) const defaultFontSizeStr = typography.label.font_size || "12px"; let fontSize = parseFloat(defaultFontSizeStr);
// 设置最小字号,避免太小看不清 const minFontSize = 4; // 保证最小字体是 4
// 4.2 定义一个函数,用给定的字号去测量"所有"维度文本的最大高度 function getMaxTextHeightForFontSize(testFontSize) { let maxH = 0; sortedDimensions.forEach(dim => { const textSize = chartUtils.text.measure(null, dim, { fontFamily: typography.label.font_family, fontSize: testFontSize, fontWeight: typography.label.font_weight, }); maxH = Math.max(maxH, textSize.height); }); return maxH; }
// 4.3 计算两条 bar(在 yScale 排列)之间的距离:就是 yScale.step() const barStep = yScale.step(); // 因为标���要画在 bar 底部 + 一定空隙(例如 +10 px), // 相邻两条 bar 的文字基线相差 barStep。若文字高度大于 barStep,就会挤到下一行文本 // 简单判断:若 textHeight > barStep,则判定会重叠
// 4.4 不断减小字号直到能放下或到达最小字号 while (true) { if (fontSize < minFontSize) { fontSize = minFontSize; break; } const maxTextHeight = getMaxTextHeightForFontSize(fontSize); if (maxTextHeight <= barStep) { // 说明可以放下,不会重叠 break; } fontSize--; }
// ---------- 8. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 9. 绘制条形和标签 ---------- // 获取条形颜色 const getBarColor = () => { return colorResolver.other("primary", { fallback: "#0099ff" }).value; // 默认蓝色 }; // 获取描边颜色 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.variant(getBarColor(), { mode: "darker", amount: 0.2 }); }; // ---- 动态计算维度标签位置 ---- // 计算两个条形图之间的距离 const barGap = yScale.step() - yScale.bandwidth(); // 设置一个安全的最小距离,确保标签与条形图不会重叠 const minSafeLabelDistance = Math.max(3, barGap / 4); // 调整字体大小计算部分,让它更合理地配合条形间距 function calculateOptimalFontSize() { // 计算条形之间的可用空间 (即下方空间) const availableSpaceBelow = yScale.step() - yScale.bandwidth(); // 基于可用空间估算理想字体大小 // 字体高度约等于字体大小,留一点点空隙 (e.g., 2px) const fontSizeEstimate = Math.floor(availableSpaceBelow - 2); // 限制在合理范围内,确保不小于 minFontSize return Math.max(minFontSize, Math.min(fontSize, fontSizeEstimate)); } // 调整现有的fontSize计算 fontSize = calculateOptimalFontSize(); // 为每个维度绘制条形和标签 sortedDimensions.forEach(dimension => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]); // 创建条形组 const barGroup = g.append("g") .attr("transform", `translate(0, ${yScale(dimension)})`); // 绘制条形 barGroup.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", barWidth) .attr("height", barHeight) .attr("fill", variables.has_gradient ? "url(#bar-gradient)" : getBarColor()) .attr("rx", variables.has_rounded_corners ? 3 : 0) .attr("ry", variables.has_rounded_corners ? 3 : 0) .style("stroke", variables.has_stroke ? getStrokeColor() : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none"); // 计算标签位置 - 放置在条形下方,避免重叠 const labelYPosition = barHeight + minSafeLabelDistance; // 在条形下方留出安全距离 // 添加维度标签 barGroup.append("text") .attr("x", 0) // 标签从条形左侧开始 .attr("y", labelYPosition) .attr("dy", "0.71em") // 调整基线使文本顶部接近labelYPosition .attr("text-anchor", "start") // 左对齐 .style("font-family", typography.label.font_family) .style("font-size", fontSize + "px") .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension); // 添加数值标签(在条形右侧) const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; barGroup.append("text") .attr("x", barWidth + 5) // 条形右侧10px .attr("y", barHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407/* REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_5_hand", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.js (样式02)function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333", other: { primary: "#0099ff" } // 默认使用蓝色作为条形颜色 }; const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 数值单位规范 // 添加数值格式化函数 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = 1; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const originalHeight = variables.height || 600; // 设置边距 - 这个样式需要更多的上部和下部空间用于标签 const margin = { top: 100, // 顶部边距 right: 80, // 右侧足够显示数值标签 bottom: 70, // 底部边距 left: 20 // 左侧边距 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; // 默认为百分比 if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ---------- // 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 按数值降序排序数据(与图片相符) const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // ---------- 5. 计算标签宽度、动态高度和图表尺寸 ---------- // 动态调整高度 const numDimensions = sortedDimensions.length; let adjustedHeight = originalHeight; const maxHeightFactor = 1.88; if (numDimensions > 18) { // 根据条目数量比例计算建议高度 const suggestedHeight = originalHeight * (numDimensions / 18); // 限制最大高度 adjustedHeight = Math.min(suggestedHeight, originalHeight * maxHeightFactor); } // 使用调整后的高度 const height = adjustedHeight; // 创建临时SVG来测量文本宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden"); // 计算最大维度标签宽度 let maxLabelWidth = 0; dimensions.forEach(dimension => { // 格式化维度名称(附加单位,如果有) const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; const textWidth = chartUtils.text.measure(tempSvg, formattedDimension, { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }).width; maxLabelWidth = Math.max(maxLabelWidth, textWidth); }); // 计算最大数值标签宽度 let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`; const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width; maxValueWidth = Math.max(maxValueWidth, textWidth); }); // 删除临时SVG tempSvg.remove(); // 根据标签宽度调整右边距 margin.right = Math.max(margin.right, maxValueWidth + 10); // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = height - margin.top - margin.bottom; // ---------- 6. 创建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"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 添加渐变(如果启用) if (variables.has_gradient) { const primaryColor = colorResolver.other("primary", { fallback: "#0099ff" }).value; const gradient = defs.append("linearGradient") .attr("id", "bar-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.5 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", d3.rgb(primaryColor)); } // ---------- 7. 创建比例尺 ---------- // 计算条形的额外间距(如果启用) const barPadding = variables.has_spacing ? 0.7 : 0.6 ; // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.1]) // 添加10%边距 .range([0, innerWidth]); // ---------- 4. 在"正式渲染"前,测量合适的维度标签字体大小 ----------
// 4.1 从 typography.label.font_size 中解析初始字号(可能是 "12px" 这种写法) const defaultFontSizeStr = typography.label.font_size || "12px"; let fontSize = parseFloat(defaultFontSizeStr);
// 设置最小字号,避免太小看不清 const minFontSize = 4; // 保证最小字体是 4
// 4.2 定义一个函数,用给定的字号去测量"所有"维度文本的最大高度 function getMaxTextHeightForFontSize(testFontSize) { let maxH = 0; sortedDimensions.forEach(dim => { const textSize = chartUtils.text.measure(null, dim, { fontFamily: typography.label.font_family, fontSize: testFontSize, fontWeight: typography.label.font_weight, }); maxH = Math.max(maxH, textSize.height); }); return maxH; }
// 4.3 计算两条 bar(在 yScale 排列)之间的距离:就是 yScale.step() const barStep = yScale.step(); // 因为标签要画在 bar 底部 + 一定空隙(例如 +10 px), // 相邻两条 bar 的文字基线相差 barStep。若文字高度大于 barStep,就会挤到下一行文本 // 简单判断:若 textHeight > barStep,则判定会重叠
// 4.4 不断减小字号直到能放下或到达最小字号 while (true) { if (fontSize < minFontSize) { fontSize = minFontSize; break; } const maxTextHeight = getMaxTextHeightForFontSize(fontSize); if (maxTextHeight <= barStep) { // 说明可以放下,不会重叠 break; } fontSize--; }
// ---------- 8. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 9. 绘制条形和标签 ---------- // 获取条形颜色 const getBarColor = () => { return colorResolver.other("primary", { fallback: "#0099ff" }).value; // 默认蓝色 }; // 获取描边颜色 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.variant(getBarColor(), { mode: "darker", amount: 0.2 }); }; // ---- 动态计算维度标签位置 ---- // 计算两个条形图之间的距离 const barGap = yScale.step() - yScale.bandwidth(); // 设置一个安全的最小距离,确保标签与条形图不会重叠 const minSafeLabelDistance = Math.max(3, barGap / 4); // 调整字体大小计算部分,让它更合理地配合条形间距 function calculateOptimalFontSize() { // 计算条形之间的可用空间 (即下方空间) const availableSpaceBelow = yScale.step() - yScale.bandwidth(); // 基于可用空间估算理想字体大小 // 字体高度约等于字体大小,留一点点空隙 (e.g., 2px) const fontSizeEstimate = Math.floor(availableSpaceBelow - 2); // 限制在合理范围内,确保不小于 minFontSize return Math.max(minFontSize, Math.min(fontSize, fontSizeEstimate)); } // 调整现有的fontSize计算 fontSize = calculateOptimalFontSize(); // 为每个维度绘制条形和标签 sortedDimensions.forEach(dimension => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]); // 创建条形组 const barGroup = g.append("g") .attr("transform", `translate(0, ${yScale(dimension)})`); // 绘制条形 barGroup.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", barWidth) .attr("height", barHeight) .attr("fill", variables.has_gradient ? "url(#bar-gradient)" : getBarColor()) .attr("rx", variables.has_rounded_corners ? 3 : 0) .attr("ry", variables.has_rounded_corners ? 3 : 0) .style("stroke", variables.has_stroke ? getStrokeColor() : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none"); // 计算标签位置 - 放置在条形下方,避免重叠 const labelYPosition = barHeight + minSafeLabelDistance; // 在条形下方留出安全距离 // 添加维度标签 barGroup.append("text") .attr("x", 0) // 标签从条形左侧开始 .attr("y", labelYPosition) .attr("dy", "0.71em") // 调整基线使文本顶部接近labelYPosition .attr("text-anchor", "start") // 左对齐 .style("font-family", typography.label.font_family) .style("font-size", fontSize + "px") .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(dimension); // 添加数值标签(在条形右侧) const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; barGroup.append("text") .attr("x", barWidth + 5) // 条形右侧10px .attr("y", barHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedValue); } }); const roughness = 1; const bowing = 2; const fillStyle = "hachure"; const randomize = false; const pencilFilter = false; const svgConverter = new svg2roughjs.Svg2Roughjs(containerSelector); svgConverter.pencilFilter = pencilFilter; svgConverter.randomize = randomize; svgConverter.svg = svg.node(); svgConverter.roughConfig = { bowing, roughness, fillStyle }; svgConverter.sketch(); // Remove the first SVG element if it exists const firstSvg = document.querySelector(`${containerSelector} svg`); if (firstSvg) { firstSvg.remove(); } // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_7", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平条形图实现 - 使用D3.jsfunction makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像设置 const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; const height = variables.height || 600; // 设置边距 - 初始值,稍后会根据标签长度调整 const margin = { top: 60, // 顶部留出标题空间 right: 40, // 右侧足够显示数值 bottom: 30, // 底部边距 left: 80 // 左侧空间,稍后会调整 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 // 根据数据列提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key || "dimension"; const valueField = chartUtils.schema.channel(jsonData, "y").key || "value"; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; // 默认为百分比 if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; }
let valueUnit2 = ""; valueUnit2 = chartUtils.schema.channel(jsonData, "y2").unit === "none" ? "" : chartUtils.schema.channel(jsonData, "y2").unit; // ---------- 4. 数据处理 ---------- // 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 如果x维度数量超过15,每增加一个x,整个图像的高度增加3% const baseHeight = variables.height || 600; const adjustedHeight = dimensions.length > 15 ? baseHeight * (1 + (dimensions.length - 15) * 0.03) : baseHeight; // 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 // ---------- 5. 计算标签宽度 ---------- // 序号宽度 const rankingWidth = 25; // 图标尺寸 let flagWidth = 40; let flagHeight = 40; const flagPadding = 7; const labelMeasureOptions = { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }; const annotationMeasureOptions = { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }; // 计算最大维度标签���度(不包括图标和序号) let maxLabelWidth = 0; dimensions.forEach(dimension => { // 格式化维度名称(附加单位,如果有) const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; const textWidth = chartUtils.text.measure(null, formattedDimension, labelMeasureOptions).width; maxLabelWidth = Math.max(maxLabelWidth, textWidth); }); // 计算最大数值标签宽度 let maxValueWidth = 0; chartData.forEach(d => { const value = +d[valueField]; const valueText = `${chartUtils.format.autoText(value)}${valueUnit}`; const textWidth = chartUtils.text.measure(null, valueText, annotationMeasureOptions).width; maxValueWidth = Math.max(maxValueWidth, textWidth); }); // 计算左边距,考虑序号 + 标签 + 图标之间的间距 // 序号在最左边,然后是标签(右对齐),然后是图标 const totalLeftPadding = rankingWidth + maxLabelWidth + flagWidth + flagPadding * 5; margin.left = Math.max(margin.left, totalLeftPadding); margin.right = Math.max(margin.right, maxValueWidth + 10); // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = adjustedHeight - margin.top - margin.bottom; // ---------- 6. 创建SVG容器 ---------- const svg = d3.select(containerSelector) .append("svg") .attr("width", width) // 使用固定宽度而不是百分比 .attr("height", adjustedHeight) .attr("viewBox", `0 0 ${width} ${adjustedHeight}`) .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 获取主题色 const primaryColor = colorResolver.other("primary", { fallback: "#1d6b64" }).value; // 获取最大值和最小值用于颜色插值 const minValue = d3.min(chartData, d => +d[valueField]); const maxValue = d3.max(chartData, d => +d[valueField]); // 创建颜色比例尺 - 将数值映射到颜色 const colorScale = d3.scaleLinear() .domain([minValue, maxValue]) .range([colorResolver.variant(primaryColor, { mode: "brighter", amount: 0.4 }), colorResolver.variant(primaryColor, { mode: "darker", amount: 0.4 })]); // ---------- 7. 创建比例尺 ---------- // 计算条形的额外间距(如果启用) const barPadding = variables.has_spacing ? 0.3 : 0.2; // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(sortedDimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(用于数值) const xScale = d3.scaleLinear() .domain([0, d3.max(chartData, d => +d[valueField]) * 1.05]) // 添加5%边距 .range([0, innerWidth]); // ---------- 8. 创建标题和描述 ---------- // 添加图表标题(如果存在) if (jsonData.title) { svg.append("text") .attr("x", width / 2) .attr("y", 30) .attr("text-anchor", "middle") .style("font-family", typography.title.font_family) .style("font-size", typography.title.font_size) .style("font-weight", typography.title.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(jsonData.title); } // 添加图表描述(如果存在) if (jsonData.description) { svg.append("text") .attr("x", width / 2) .attr("y", 50) .attr("text-anchor", "middle") .style("font-family", typography.description.font_family) .style("font-size", typography.description.font_size) .style("font-weight", typography.description.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(jsonData.description); } // ---------- 9. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 10. 绘制条形和标签 ---------- // 获取描边颜色的辅助函数 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.available(0, { fallback: "#333333" }).value; }; // 为每个维度绘制条形和标签 sortedDimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barHeight = yScale.bandwidth(); const barWidth = xScale(+dataPoint[valueField]); // 计算此条形的颜色 - 基于其值 const barColor = colorScale(+dataPoint[valueField]); // 绘制条形 g.append("rect") .attr("x", 0) .attr("y", yScale(dimension)) .attr("width", barWidth) .attr("height", barHeight) .attr("fill", barColor) // 使用单一颜色 .attr("rx", variables.has_rounded_corners ? 3 : 0) .attr("ry", variables.has_rounded_corners ? 3 : 0) .style("stroke", variables.has_stroke ? getStrokeColor() : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); }); // 修复: 正确设置图标大小 const adjustedFlagWidth = Math.min(barHeight * 0.8, flagWidth); // 限制图标宽度 const adjustedFlagHeight = Math.min(barHeight * 0.8, flagHeight); // 限制图标高度 // 计算每个标签的位置 // 图标位置:紧贴条形左边 const iconX = -adjustedFlagWidth - flagPadding; const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; // 标签位置:在图标左侧,右对齐(相对于最长标签) const labelX = iconX - flagPadding; // 序号位置:在标签最左边,考虑最长的标签 const rankingX = labelX - maxLabelWidth - flagPadding * 2; // 2. 添加国家/地区标签和图标 if (images.field && images.field[dimension]) { // 计算裁剪圆的半径 (80% of adjustedFlagHeight/2) const clipRadius = (adjustedFlagHeight/2) * 0.8; // 为每个国家图标创建唯一的clipPath ID const clipId = `clip-${dimension.replace(/\s+/g, '-').toLowerCase()}-${index}`; // 添加剪切路径定义 const defs = g.append("defs"); defs.append("clipPath") .attr("id", clipId) .append("circle") .attr("cx", adjustedFlagWidth/2) .attr("cy", adjustedFlagHeight/2) .attr("r", clipRadius-2); // 创建一个组来包含图像和边框 const iconGroup = g.append("g") .attr("transform", `translate(${iconX}, ${yScale(dimension) + (barHeight - adjustedFlagHeight) / 2})`); // 添加黑色边框圆 - 放在图像下面但会显示在图像周围 iconGroup.append("circle") .attr("cx", adjustedFlagWidth/2) .attr("cy", adjustedFlagHeight/2) .attr("r", clipRadius) .attr("fill", "none") .attr("stroke", "#000000") .attr("stroke-width", 0.2); // 添加裁剪后的国家/地区图标 iconGroup.append("image") .attr("x", 0) .attr("y", 0) .attr("width", adjustedFlagWidth) .attr("height", adjustedFlagHeight) .attr("xlink:href", images.field[dimension]) .attr("preserveAspectRatio","xMidYMid meet") .attr("clip-path", `url(#${clipId})`); } // 添加维度标签 g.append("text") .attr("x", labelX) .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedDimension); // 添加序号 g.append("text") .attr("x", rankingX) .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("text-anchor", "end") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(`${index + 1}.`); // 格式化数值 const formattedValue = `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}`; const valueLabelFontSize = `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`; const valueTextWidth = chartUtils.text.measure(g, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: valueLabelFontSize, fontWeight: typography.annotation.font_weight }).width; // 判断是否能在条形内部放置文本(需要多留一些边距) const textFitsInside = barWidth > valueTextWidth + 20; // 添加数值标签(在条形内部或外部) g.append("text") .attr("x", textFitsInside ? barWidth - 5 : barWidth + 5) // 如果放在内部,距离条形右侧5px,否则放在外部 .attr("y", yScale(dimension) + barHeight / 2) .attr("dy", "0.35em") .attr("text-anchor", textFitsInside ? "end" : "start") // 在内部时右对齐,在外部时左对齐 .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("fill", textFitsInside ? "#ffffff" : colorResolver.text({ fallback: "#333333" }).value) // 在内部时使用白色,在外部时使用文本颜色 .text(formattedValue); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_8", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], ["-inf", "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "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, 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 baseWidth = Number(variables.width) || 620; const baseHeight = Number(variables.height) || 560; const width = Math.max(430, baseWidth); 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 = "#607184"; const headerColor = "#071f46"; const headerTextColor = "#ffffff"; const referenceGreen = "#5b8f19"; const referenceGreenLight = "#99c85e"; const referenceGreenDark = "#315f12"; const negativeColor = "#b94452"; const panelFill = "#fdfefe"; const plotFill = "#f6fbfd"; const rowAltFill = "#edf6f2"; const trackColor = "#e6f0ea"; const gridColor = "rgba(35, 70, 95, 0.13)"; const labelSize = Math.max(8.8, Math.min(10.2, parseFloat(typography.label?.font_size) || 10)); const valueSize = Math.max(8.2, Math.min(9.6, parseFloat(typography.annotation?.font_size) || 9.4)); const labelWeight = typography.label?.font_weight || "700"; const valueWeight = typography.annotation?.font_weight || "650";
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", "horizontal-bar-chart-8");
const safeId = chartUtils.random.value(jsonData, "horizontal_bar_chart_8").toString(36).slice(2, 10); const positiveGradientId = `horizontal-bar-8-positive-${safeId}`; const negativeGradientId = `horizontal-bar-8-negative-${safeId}`; const defs = svg.append("defs"); defs.append("linearGradient") .attr("id", positiveGradientId) .attr("x1", "0%") .attr("x2", "100%") .attr("y1", "0%") .attr("y2", "0%") .selectAll("stop") .data([ { offset: "0%", color: referenceGreenDark }, { offset: "54%", color: referenceGreen }, { offset: "100%", color: referenceGreenLight } ]) .enter() .append("stop") .attr("offset", d => d.offset) .attr("stop-color", d => d.color); defs.append("linearGradient") .attr("id", negativeGradientId) .attr("x1", "100%") .attr("x2", "0%") .attr("y1", "0%") .attr("y2", "0%") .selectAll("stop") .data([ { offset: "0%", color: negativeColor }, { offset: "100%", color: "#f97373" } ]) .enter() .append("stop") .attr("offset", d => d.offset) .attr("stop-color", d => d.color);
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 horizontal bar 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 }; const seasons = { winter: 1, spring: 2, summer: 3, fall: 4, autumn: 4 }; 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) || text.match(/^(-?\d{4})\s+Q([1-4])$/i); if (match && text.toUpperCase().startsWith("Q")) return Number(match[2]) * 10 + Number(match[1]); if (match) return Number(match[1]) * 10 + Number(match[2]); match = text.match(/^(winter|spring|summer|fall|autumn)\s+(-?\d{4})$/i); if (match) return Number(match[2]) * 10 + seasons[match[1].toLowerCase()]; match = text.match(/^(-?\d{4})\s+(winter|spring|summer|fall|autumn)$/i); if (match) return Number(match[1]) * 10 + seasons[match[2].toLowerCase()]; return NaN; }
function parseOrdinalRank(value) { const text = String(value ?? "").trim().toLowerCase(); const named = { primary: 1, elementary: 1, secondary: 2, college: 3, university: 3, low: 1, lower: 1, medium: 2, moderate: 2, high: 3, higher: 3, children: 1, adolescents: 2, teens: 2, adults: 3, seniors: 4 }; if (named[text] != null) return named[text]; let match = text.match(/(?:less than|under)\s*[$]?\s*([\d,]+)/); if (match) return Number(match[1].replace(/,/g, "")) - 0.5; match = text.match(/(?:more than|over)\s*[$]?\s*([\d,]+)/); if (match) return Number(match[1].replace(/,/g, "")) + 0.5; match = text.match(/^[$]?\s*([\d,]+(?:\.\d+)?)\s*(?:-|to)/); if (match) return Number(match[1].replace(/,/g, "")); 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("$")) { const sign = numeric < 0 ? "-" : ""; return `${sign}$${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 grouped = new Map(); sourceRows.forEach((row, index) => { const category = readableLabel(row[categoryField]); const value = Number(row[valueField]); if (!category || !Number.isFinite(value)) return; if (!grouped.has(category)) { grouped.set(category, { category, rawCategory: row[categoryField], firstIndex: index, value: 0 }); } grouped.get(category).value += value; });
const rows = Array.from(grouped.values()).map(row => ({ ...row, temporalRank: parseTemporalRank(row.rawCategory), ordinalRank: parseOrdinalRank(row.rawCategory) })); if (!rows.length) return message("No valid data for horizontal bars");
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); });
function fittedFontSize(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))); }
const rowHeight = rows.length > 18 ? 24 : (rows.length > 12 ? 28 : 35); const cardX = 8; const cardY = 8; const cardWidth = width - cardX * 2; const cardPad = 18; const metaY = cardY + 15; const headerY = cardY + 61; const headerHeight = 31; const top = headerY + headerHeight + 12; const footerHeight = 86; const footerGap = 34; const markerColumnWidth = 32; const valueColumnWidth = Math.min(Math.max(78, width * 0.17), 118); const labelColumnWidth = Math.min(Math.max(132, width * 0.31), 212); const tableX = cardX + cardPad; const tableWidth = cardWidth - cardPad * 2; const left = tableX + markerColumnWidth + labelColumnWidth; const valueColumnX = tableX + tableWidth - valueColumnWidth; const innerWidth = Math.max(160, valueColumnX - left - 16); const innerHeight = Math.max(145, rows.length * rowHeight); const footerY = top + innerHeight + footerGap; const height = Math.max(baseHeight, footerY + footerHeight + 18); const cardHeight = height - cardY * 2; svg.attr("height", height).attr("viewBox", `0 0 ${width} ${height}`);
const minValue = d3.min(rows, d => d.value) || 0; const maxValue = d3.max(rows, d => d.value) || 0; const span = Math.max(1, maxValue - minValue); const xDomain = [ Math.min(0, minValue - span * 0.08), Math.max(0, maxValue + span * 0.12) ]; const xScale = d3.scaleLinear() .domain(xDomain) .nice(5) .range([0, innerWidth]); const yScale = d3.scaleBand() .domain(rows.map(d => d.category)) .range([0, innerHeight]) .padding(rows.length > 14 ? 0.31 : 0.25); const zeroX = xScale(0); const barHeight = Math.max(5.5, yScale.bandwidth()); const categoryMaxWidth = Math.max(48, labelColumnWidth - 14); const axisTitle = readableLabel(valueColumn.label || valueField || valueColumn.description); const categoryTitle = readableLabel(categoryColumn.label || categoryField); const valueHeader = valueUnit ? `Value (${valueUnit})` : "Value";
svg.append("rect") .attr("class", "chart-style-panel") .attr("x", cardX) .attr("y", cardY) .attr("width", cardWidth) .attr("height", cardHeight) .attr("rx", 10) .attr("fill", panelFill) .attr("stroke", "rgba(44, 82, 112, 0.15)");
svg.append("rect") .attr("class", "reference-icon-slot chart-icon-slot") .attr("data-slot", "icon") .attr("x", tableX) .attr("y", metaY - 2) .attr("width", 34) .attr("height", 34) .attr("rx", 8) .attr("fill", "#eef6e7") .attr("stroke", "rgba(49, 95, 18, 0.22)");
svg.append("circle") .attr("class", "reference-icon-slot-glyph") .attr("cx", tableX + 17) .attr("cy", metaY + 15) .attr("r", 8) .attr("fill", referenceGreen) .attr("fill-opacity", 0.88);
svg.append("text") .attr("class", "scale-note") .attr("x", tableX + 47) .attr("y", metaY + 10) .attr("fill", headerColor) .style("font-family", annotationFamily) .style("font-size", `${Math.max(7.4, valueSize - 0.8)}px`) .style("font-weight", "750") .text(truncateText(`${axisTitle}`, Math.max(28, Math.floor((cardWidth - 190) / 5.2))));
svg.append("text") .attr("class", "category-note") .attr("x", tableX + 47) .attr("y", metaY + 27) .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", `${Math.max(7.1, valueSize - 1.2)}px`) .text(`${categoryTitle} order: ${sortMode}`);
const decorSlotX = cardX + cardWidth - 93; svg.append("rect") .attr("class", "reference-decorative-image-slot decorative-image-slot") .attr("data-slot", "decorative-image") .attr("x", decorSlotX) .attr("y", metaY - 3) .attr("width", 70) .attr("height", 41) .attr("rx", 9) .attr("fill", "#f4f8fb") .attr("stroke", "rgba(49, 95, 18, 0.18)");
svg.append("path") .attr("class", "reference-decorative-image-slot-mark") .attr("d", `M${decorSlotX + 9},${metaY + 27} C${decorSlotX + 23},${metaY + 8} ${decorSlotX + 39},${metaY + 33} ${decorSlotX + 61},${metaY + 13}`) .attr("fill", "none") .attr("stroke", referenceGreenLight) .attr("stroke-width", 4) .attr("stroke-linecap", "round");
svg.append("rect") .attr("class", "chart-style-header-rule table-header") .attr("x", tableX) .attr("y", headerY) .attr("width", tableWidth) .attr("height", headerHeight) .attr("rx", 4) .attr("fill", headerColor);
svg.append("text") .attr("class", "table-header-label category-header-label") .attr("x", tableX + markerColumnWidth + 2) .attr("y", headerY + headerHeight / 2 + 0.5) .attr("dominant-baseline", "middle") .attr("fill", headerTextColor) .style("font-family", annotationFamily) .style("font-size", `${Math.max(7.7, valueSize - 0.4)}px`) .style("font-weight", "800") .text(truncateText(categoryTitle, 22));
svg.append("text") .attr("class", "table-header-label axis-title") .attr("x", left + innerWidth / 2) .attr("y", headerY + headerHeight / 2 + 0.5) .attr("text-anchor", "middle") .attr("dominant-baseline", "middle") .attr("fill", headerTextColor) .style("font-family", annotationFamily) .style("font-size", `${Math.max(7.7, valueSize - 0.4)}px`) .style("font-weight", "800") .text(truncateText(axisTitle, Math.max(20, Math.floor(innerWidth / 5.2))));
svg.append("text") .attr("class", "table-header-label value-header-label") .attr("x", valueColumnX + valueColumnWidth - 8) .attr("y", headerY + headerHeight / 2 + 0.5) .attr("text-anchor", "end") .attr("dominant-baseline", "middle") .attr("fill", headerTextColor) .style("font-family", annotationFamily) .style("font-size", `${Math.max(7.7, valueSize - 0.4)}px`) .style("font-weight", "800") .text(truncateText(valueHeader, 18));
svg.append("rect") .attr("class", "plot-background") .attr("x", tableX) .attr("y", top - 7) .attr("width", tableWidth) .attr("height", innerHeight + 14) .attr("rx", 5) .attr("fill", plotFill) .attr("stroke", "rgba(91, 123, 148, 0.10)");
svg.append("line") .attr("class", "table-column-rule label-plot-rule") .attr("x1", left - 12) .attr("x2", left - 12) .attr("y1", headerY) .attr("y2", top + innerHeight + 7) .attr("stroke", "rgba(7, 31, 70, 0.15)") .attr("stroke-width", 1);
svg.append("line") .attr("class", "table-column-rule value-column-rule") .attr("x1", valueColumnX - 8) .attr("x2", valueColumnX - 8) .attr("y1", headerY) .attr("y2", top + innerHeight + 7) .attr("stroke", "rgba(7, 31, 70, 0.15)") .attr("stroke-width", 1);
const rowLayer = svg.append("g") .attr("class", "bar-row-backgrounds");
const plot = svg.append("g") .attr("class", "horizontal-bar-plot") .attr("transform", `translate(${left}, ${top})`);
let xTicks = xScale.ticks(5); if (!xTicks.some(tick => Math.abs(tick) < 1e-9)) xTicks.push(0); xTicks = Array.from(new Set(xTicks.map(tick => Number(tick.toPrecision(12))))).sort((a, b) => a - b);
xTicks.forEach(tick => { const x = xScale(tick); plot.append("line") .attr("class", "gridline x-axis-gridline") .attr("x1", x) .attr("x2", x) .attr("y1", 0) .attr("y2", innerHeight) .attr("stroke", Math.abs(tick) < 1e-9 ? "rgba(7, 31, 70, 0.42)" : gridColor) .attr("stroke-width", Math.abs(tick) < 1e-9 ? 1.15 : 0.85); plot.append("text") .attr("class", "x-axis-tick") .attr("x", x) .attr("y", innerHeight + 20) .attr("text-anchor", "middle") .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", `${Math.max(6.8, valueSize - 1.3)}px`) .style("font-weight", "650") .text(formatLocalValue(tick, valueUnit)); });
plot.append("line") .attr("class", "axis-line zero-line") .attr("x1", zeroX) .attr("x2", zeroX) .attr("y1", 0) .attr("y2", innerHeight) .attr("stroke", "#475569") .attr("stroke-width", 1.45);
rows.forEach((row, index) => { const y = yScale(row.category); const centerY = y + yScale.bandwidth() / 2; const value = row.value; const x0 = xScale(Math.min(0, value)); const x1 = xScale(Math.max(0, value)); const barX = Math.min(x0, x1); const widthValue = Math.max(1, Math.abs(x1 - x0)); const fill = value < 0 ? `url(#${negativeGradientId})` : `url(#${positiveGradientId})`; const markerFill = d3.interpolateRgb(referenceGreenDark, referenceGreenLight)(rows.length <= 1 ? 0 : index / (rows.length - 1)); const rowBackgroundY = top + y - Math.max(3, (rowHeight - yScale.bandwidth()) / 2); const rowBackgroundHeight = Math.min(rowHeight - 2, yScale.bandwidth() + 7); const absoluteCenterY = top + centerY; const categoryFontSize = fittedFontSize(row.category, categoryMaxWidth, labelSize, 7.0);
rowLayer.append("rect") .attr("class", "bar-row-background") .attr("data-source-index", row.firstIndex) .attr("data-category", row.category) .attr("data-value", row.value) .attr("x", tableX) .attr("y", rowBackgroundY) .attr("width", tableWidth) .attr("height", rowBackgroundHeight) .attr("rx", 4) .attr("fill", index % 2 === 0 ? "#ffffff" : rowAltFill);
plot.append("rect") .attr("class", "bar-track") .attr("data-source-index", row.firstIndex) .attr("data-category", row.category) .attr("data-value", row.value) .attr("x", 0) .attr("y", centerY - barHeight * 0.34) .attr("width", innerWidth) .attr("height", Math.max(4.8, barHeight * 0.68)) .attr("rx", Math.min(8, barHeight / 2)) .attr("ry", Math.min(8, barHeight / 2)) .attr("fill", trackColor);
plot.append("rect") .attr("class", "horizontal-bar data-point mark") .attr("data-source-index", row.firstIndex) .attr("data-category", row.category) .attr("data-value", row.value) .attr("x", barX) .attr("y", centerY - barHeight * 0.34) .attr("width", widthValue) .attr("height", Math.max(4.8, barHeight * 0.68)) .attr("rx", Math.min(8, barHeight / 2)) .attr("ry", Math.min(8, barHeight / 2)) .attr("fill", fill) .attr("fill-opacity", index === 0 && !allTemporal ? 0.98 : 0.94);
const valueText = formatLocalValue(value, valueUnit); const barEndX = left + (value >= 0 ? x1 : x0); svg.append("line") .attr("class", "value-leader") .attr("data-source-index", row.firstIndex) .attr("data-category", row.category) .attr("data-value", row.value) .attr("x1", Math.max(left, Math.min(valueColumnX - 16, barEndX + (value >= 0 ? 4 : -4)))) .attr("x2", valueColumnX - 13) .attr("y1", absoluteCenterY) .attr("y2", absoluteCenterY) .attr("stroke", "rgba(49, 95, 18, 0.18)") .attr("stroke-dasharray", "2 4") .attr("stroke-width", 1);
svg.append("text") .attr("class", "value-label") .attr("data-source-index", row.firstIndex) .attr("data-category", row.category) .attr("data-value", row.value) .attr("x", valueColumnX + valueColumnWidth - 8) .attr("y", absoluteCenterY) .attr("text-anchor", "end") .attr("dominant-baseline", "middle") .attr("fill", headerColor) .style("font-family", annotationFamily) .style("font-size", `${fittedFontSize(valueText, valueColumnWidth - 14, valueSize, 6.9)}px`) .style("font-weight", valueWeight) .text(valueText);
svg.append("circle") .attr("class", "category-index-dot") .attr("data-source-index", row.firstIndex) .attr("data-category", row.category) .attr("data-value", row.value) .attr("cx", tableX + 15) .attr("cy", absoluteCenterY) .attr("r", Math.max(4.5, Math.min(6.0, barHeight * 0.30))) .attr("fill", markerFill) .attr("stroke", "rgba(255, 255, 255, 0.86)") .attr("stroke-width", 1.2);
svg.append("text") .attr("class", "category-label y-axis-tick") .attr("data-source-index", row.firstIndex) .attr("data-category", row.category) .attr("data-value", row.value) .attr("x", tableX + markerColumnWidth) .attr("y", absoluteCenterY) .attr("text-anchor", "start") .attr("dominant-baseline", "middle") .attr("fill", textColor) .style("font-family", fontFamily) .style("font-size", `${categoryFontSize}px`) .style("font-weight", labelWeight) .text(row.category); });
const footer = svg.append("g") .attr("class", "reference-footer-card") .attr("transform", `translate(${tableX}, ${footerY})`);
footer.append("rect") .attr("class", "footer-card") .attr("x", 0) .attr("y", 0) .attr("width", tableWidth) .attr("height", footerHeight) .attr("rx", 8) .attr("fill", "#f7fbf1") .attr("stroke", "rgba(49, 95, 18, 0.16)");
const footerItems = [ { label: "Scale", text: `${formatLocalValue(xScale.domain()[0], valueUnit)} to ${formatLocalValue(xScale.domain()[1], valueUnit)}` }, { label: "Order", text: sortMode }, { label: "Source", text: truncateText(categoryTitle, 28) } ]; const footerItemWidth = tableWidth / footerItems.length; footerItems.forEach((item, index) => { const itemX = index * footerItemWidth; if (index > 0) { footer.append("line") .attr("class", "footer-divider") .attr("x1", itemX) .attr("x2", itemX) .attr("y1", 14) .attr("y2", footerHeight - 14) .attr("stroke", "rgba(49, 95, 18, 0.16)") .attr("stroke-width", 1); } footer.append("rect") .attr("class", "footer-icon-slot") .attr("data-slot", `footer-icon-${index + 1}`) .attr("x", itemX + 15) .attr("y", 18) .attr("width", 24) .attr("height", 24) .attr("rx", 6) .attr("fill", "#ffffff") .attr("stroke", "rgba(49, 95, 18, 0.22)"); footer.append("circle") .attr("class", "footer-icon-slot-dot") .attr("cx", itemX + 27) .attr("cy", 30) .attr("r", 5) .attr("fill", index === 0 ? referenceGreen : (index === 1 ? referenceGreenLight : headerColor)) .attr("fill-opacity", 0.84); footer.append("text") .attr("class", "footer-label") .attr("x", itemX + 48) .attr("y", 29) .attr("dominant-baseline", "middle") .attr("fill", headerColor) .style("font-family", annotationFamily) .style("font-size", `${Math.max(7.6, valueSize - 0.7)}px`) .style("font-weight", "800") .text(item.label); footer.append("text") .attr("class", "footer-value") .attr("x", itemX + 48) .attr("y", 52) .attr("dominant-baseline", "middle") .attr("fill", mutedText) .style("font-family", annotationFamily) .style("font-size", `${Math.max(7.1, valueSize - 1.15)}px`) .style("font-weight", "600") .text(truncateText(item.text, Math.max(16, Math.floor((footerItemWidth - 58) / 4.6)))); });
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406/* REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Bar Chart", "chart_name": "horizontal_bar_chart_9", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 30], [0, "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": ["x"], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 多彩水平条形图实现 - 带百分比延伸背景 - 使用D3.jsfunction makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置 const typography = jsonData.typography || { // 字体设置,如果不存在则使用默认值 title: { font_family: "Arial", font_size: "18px", font_weight: "bold" }, label: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, description: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "14px", font_weight: "normal" } }; const colors = jsonData.colors || { text_color: "#333333", other: { primary: "#1E88E5" }, // 默认主色 field: {} // 各维度颜色 }; const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 设置视觉效果变量的默认值 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 设置延伸条形的颜色(浅蓝色) const extensionColor = "#e6f0fa"; // 浅蓝色背景 // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸 const width = variables.width || 800; // 使用调整后的高度 // const height = variables.height || 600; // 设置边距 - 后面会根据标签宽度调整左侧边距 const margin = { top: 90, // 顶部边距 right: 60, // 右侧边距,留足空间放置数值 bottom: 60, // 底部边距 left: 120 // 左侧边距,初始值,将根据标签长度调整 }; // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; // 默认为空 if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } // ---------- 4. 数据处理 ---------- // 获取唯一维度值并按数值降序排列数据 const dimensions = [...new Set(chartData.map(d => d[dimensionField]))]; // 如果x维度数量超过15,每增加一个x,整个图像的高度增加3% const baseHeight = variables.height || 600; const adjustedHeight = dimensions.length > 15 ? baseHeight * (1 + (dimensions.length - 15) * 0.03) : baseHeight; // 按数值降序排序数据 const sortedData = [...chartData].sort((a, b) => +b[valueField] - +a[valueField]); const sortedDimensions = sortedData.map(d => d[dimensionField]); // 添加数值格式化函数 // ---------- 5. 测量标签宽度和调整布局 ---------- // 创建临时SVG来测量文本宽度 const tempSvg = d3.select(containerSelector) .append("svg") .attr("width", 0) .attr("height", 0) .style("visibility", "hidden"); // Original code section for measuring label width and adjusting margin // Replace with this modified version: // 函数:测量文本宽度 function measureTextWidth(text, fontFamily, fontSize, fontWeight) { return chartUtils.text.measure(tempSvg, text, { fontFamily: fontFamily, fontSize: parseFloat(fontSize) || fontSize, fontWeight: fontWeight }).width; } // 计算最大维度标签宽度 let maxLabelWidth = 0; dimensions.forEach(dimension => { // 测量每个维度标签的宽度 const textWidth = measureTextWidth( dimension, typography.label.font_family, typography.label.font_size, typography.label.font_weight ); maxLabelWidth = Math.max(maxLabelWidth, textWidth); });
// 限制最大标签宽度为200px maxLabelWidth = Math.min(maxLabelWidth, 200);
// 调整左侧边距,确保有足够的空间显示标签 margin.left = Math.max(margin.left, maxLabelWidth + 30);
// 添加文本换行函数 function wrapText(text, maxWidth, fontFamily, fontSize, fontWeight) { // 如果文本不需要换行,直接返回 const textWidth = measureTextWidth(text, fontFamily, fontSize, fontWeight); if (textWidth <= maxWidth) { return [text]; } // 分割文本为词语数组 const words = text.split(/\s+/); const lines = []; let currentLine = words[0]; for (let i = 1; i < words.length; i++) { const word = words[i]; const width = measureTextWidth(currentLine + " " + word, fontFamily, fontSize, fontWeight); if (width <= maxWidth) { currentLine += " " + word; } else { lines.push(currentLine); currentLine = word; } } // 添加最后一行 lines.push(currentLine); // 如果没有空格分隔词(如中文),则按字符分割 if (lines.length === 1 && measureTextWidth(lines[0], fontFamily, fontSize, fontWeight) > maxWidth) { const chars = text.split(''); lines.length = 0; currentLine = chars[0]; for (let i = 1; i < chars.length; i++) { const char = chars[i]; const width = measureTextWidth(currentLine + char, fontFamily, fontSize, fontWeight); if (width <= maxWidth) { currentLine += char; } else { lines.push(currentLine); currentLine = char; } } // 添加最后一行 lines.push(currentLine); } return lines; } // 计算最大数值标签宽度 let maxValueWidth = 0; chartData.forEach(d => { const formattedValue = valueUnit ? `${chartUtils.format.autoText(+d[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+d[valueField])}`; const textWidth = chartUtils.text.measure(tempSvg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: typography.annotation.font_size, fontWeight: typography.annotation.font_weight }).width; maxValueWidth = Math.max(maxValueWidth, textWidth); }); // 删除临时SVG tempSvg.remove(); // 计算内部绘图区域尺寸 const innerWidth = width - margin.left - margin.right; const innerHeight = adjustedHeight - margin.top - margin.bottom; // ---------- 6. 创建SVG容器 ---------- const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", adjustedHeight) .attr("viewBox", `0 0 ${width} ${adjustedHeight}`) .attr("style", "max-width: 100%; height: auto;") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink"); // 添加defs用于视觉效果 const defs = svg.append("defs"); // 添加阴影滤镜(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 3); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // ---------- 7. 创建比例尺 ---------- // 计算条形的额外间距(如果启用) const barPadding = variables.has_spacing ? 0.3 : 0.2; // Y轴比例尺(用于维度) const yScale = d3.scaleBand() .domain(dimensions) .range([0, innerHeight]) .padding(barPadding); // X轴比例尺(用于数值)- 0-100% const xScale = d3.scaleLinear() .domain([0, 100]) .range([0, innerWidth]); // ---------- 8. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left}, ${margin.top})`); // ---------- 9. 绘制延伸背景和条形 ---------- // 为每个维度绘制条形 dimensions.forEach((dimension, index) => { const dataPoint = chartData.find(d => d[dimensionField] === dimension); if (dataPoint) { const barHeight = yScale.bandwidth(); const value = +dataPoint[valueField]; const barWidth = xScale(value); // 获取条形颜色 - 从colors.field中获取,如果不存在则使用默认主色 let barColor = colorResolver.other("primary").value; barColor = colorResolver.field(dimension, 0, { fallback: barColor }).value; // 创建条形组 const barGroup = g.append("g") .attr("transform", `translate(0, ${yScale(dimension)})`); // 绘制100%延伸背景 barGroup.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", innerWidth) .attr("height", barHeight) .attr("class","background") .attr("fill", extensionColor) .attr("rx", variables.has_rounded_corners ? 4 : 0) .attr("ry", variables.has_rounded_corners ? 4 : 0); // 绘制实际数值条形 barGroup.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", barWidth) .attr("height", barHeight) .attr("fill", variables.has_gradient ? d3.interpolateRgb(barColor, colorResolver.variant(barColor, { mode: "brighter", amount: 0.5 }))(0.5) : barColor) .attr("rx", variables.has_rounded_corners ? 4 : 0) .attr("ry", variables.has_rounded_corners ? 4 : 0) .style("stroke", variables.has_stroke ? colorResolver.variant(barColor, { mode: "darker", amount: 0.2 }) : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none"); // 计算动态字体大小(条形高度的60%) const dynamicFontSize = `${barHeight * 0.4}px`; // 格式化数值用于显示(根据条形是否有足够空间决定显示位置) const formattedValue = valueUnit ? `${chartUtils.format.autoText(value)}${valueUnit}` : `${chartUtils.format.autoText(value)}`; const valueTextWidth = chartUtils.text.measure(svg, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: dynamicFontSize, fontWeight: typography.annotation.font_weight }).width; // 判断数值标签是否能放入条形内 const labelFitsInside = valueTextWidth + 10 < barWidth; // 添加数值标签(使用动态字体大小) if (labelFitsInside) { // 标签放在条形内部左侧 barGroup.append("text") .attr("x", barWidth - 5) // 条形内左侧5px .attr("y", barHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "end") .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", "#FFFFFF") // 白色 .text(formattedValue); } else { // 标签放在条形外部左侧 barGroup.append("text") .attr("x", barWidth + 5) // 条形外左侧5px .attr("y", barHeight / 2) .attr("dy", "0.35em") // 垂直居中 .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", dynamicFontSize) .style("font-weight", typography.annotation.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) // 使用文本颜色 .text(formattedValue); } const wrappedText = wrapText( dimension, maxLabelWidth, typography.label.font_family, typography.label.font_size, typography.label.font_weight ); // 计算行高 const lineHeight = parseInt(typography.label.font_size) * 1.2; // 计算文本总高度 const textHeight = wrappedText.length * lineHeight; // 创建文本组 const labelGroup = barGroup.append("g") .attr("transform", `translate(${-maxLabelWidth - 10}, ${barHeight / 2 - textHeight / 2 + lineHeight / 2})`); // 添加每一行文本 wrappedText.forEach((line, i) => { labelGroup.append("text") .attr("x", 0) .attr("y", i * lineHeight) .attr("text-anchor", "start") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(line); }); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Diverging Bar Chart", "chart_name": "horizontal_diverging_bar_chart_01", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 20], ["-inf", "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary","secondary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "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 jsonData = data; const rawData = (jsonData.data && jsonData.data.data) ? jsonData.data.data : []; const variables = jsonData.variables || {}; 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" } }; const colorResolver = chartUtils.color.resolver(jsonData);
d3.select(containerSelector).html("");
const width = variables.width || 800; const height = variables.height || 600; const dimensionChannel = chartUtils.schema.channel(jsonData, "x", { fallbackKey: "dimension" }); const valueChannel = chartUtils.schema.channel(jsonData, "y", { fallbackKey: "value" }); const dimensionField = dimensionChannel.key; const valueField = valueChannel.key; const valueUnit = valueChannel.unit || "";
const rows = rawData .map((d, index) => ({ raw: d, index, label: String(d[dimensionField]), value: +d[valueField] })) .filter(d => Number.isFinite(d.value)) .sort((a, b) => a.value - b.value);
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("data-chart", "horizontal_diverging_bar_chart_01") .attr("data-reference-style", "table-diverging-bars");
const defs = svg.append("defs"); const shadow = defs.append("filter") .attr("id", "hdbar01-panel-shadow") .attr("x", "-12%") .attr("y", "-12%") .attr("width", "124%") .attr("height", "128%"); shadow.append("feDropShadow") .attr("dx", 0) .attr("dy", 8) .attr("stdDeviation", 7) .attr("flood-color", "#8fb5ca") .attr("flood-opacity", 0.24);
const headerGradient = defs.append("linearGradient") .attr("id", "hdbar01-header-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); headerGradient.append("stop").attr("offset", "0%").attr("stop-color", "#073f6e"); headerGradient.append("stop").attr("offset", "100%").attr("stop-color", "#3454d1");
const cueLowColor = "#18a75b"; const cueMidColor = "#f3c736"; const cueHighColor = "#e6372f"; const cueGradient = defs.append("linearGradient") .attr("id", "hdbar01-cue-gradient") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "0%") .attr("y2", "100%"); cueGradient.append("stop").attr("offset", "0%").attr("stop-color", cueLowColor); cueGradient.append("stop").attr("offset", "48%").attr("stop-color", cueMidColor); cueGradient.append("stop").attr("offset", "100%").attr("stop-color", cueHighColor);
if (!rows.length) { svg.append("text") .attr("x", width / 2) .attr("y", height / 2) .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", "18px") .style("fill", colorResolver.text({ fallback: "#183153" }).value) .text("No data"); return svg.node(); }
const maxAbsValue = d3.max(rows, d => Math.abs(d.value)) || 1; const minValue = d3.min(rows, d => d.value) || 0; const maxValue = d3.max(rows, d => d.value) || 0;
const chartMargin = { top: Math.max(18, height * 0.035), right: Math.max(20, width * 0.035), bottom: Math.max(16, height * 0.03), left: Math.max(72, width * 0.13) }; const cueX = Math.max(36, chartMargin.left * 0.56); const tableX = chartMargin.left + Math.max(22, width * 0.03); const tableY = chartMargin.top + Math.max(8, height * 0.015); const tableW = width - tableX - chartMargin.right; const tableH = height - tableY - chartMargin.bottom; const headerH = Math.max(44, Math.min(64, tableH * 0.13)); const bodyY = tableY + headerH; const bodyH = tableH - headerH; const rowH = bodyH / rows.length; const iconR = Math.max(9, Math.min(18, rowH * 0.27)); const panelRadius = Math.max(14, Math.min(22, width * 0.028)); const methodW = tableW * 0.42; const dividerX = tableX + methodW; const iconX = tableX + Math.max(24, tableW * 0.075); const labelX = iconX + iconR + Math.max(15, tableW * 0.035); const labelW = dividerX - labelX - 14; const barStart = dividerX + Math.max(18, tableW * 0.035); const valueAreaRight = tableX + tableW - Math.max(20, tableW * 0.03); const maxValueTextWidth = Math.max(56, tableW * 0.10); const barMaxW = Math.max(36, valueAreaRight - maxValueTextWidth - barStart - 10); const negativeMax = Math.abs(Math.min(0, minValue)); const positiveMax = Math.max(0, maxValue); const signedTotal = Math.max(1e-6, negativeMax + positiveMax); const negativeSpan = Math.max(negativeMax > 0 ? 18 : 0, barMaxW * (negativeMax / signedTotal)); const positiveSpan = Math.max(positiveMax > 0 ? 18 : 0, barMaxW - negativeSpan); const barZeroX = barStart + negativeSpan; const trackH = Math.max(7, Math.min(20, rowH * 0.34)); const labelFont = Math.max(11, Math.min(16, rowH * 0.27)); const valueFont = Math.max(13, Math.min(21, rowH * 0.34)); const unitFont = Math.max(8, Math.min(13, valueFont * 0.58)); const textColor = colorResolver.text({ fallback: "#092144" }).value || "#092144"; const cueEndpointR = Math.max(16, iconR * 1.25); const contentBgInsetX = Math.max(18, width * 0.023); const contentBgInsetY = Math.max(10, height * 0.016); const contentBgW = width - contentBgInsetX * 2; const contentVisualLeft = cueX - cueEndpointR; const contentVisualRight = tableX + tableW; const contentVisualCenter = (contentVisualLeft + contentVisualRight) / 2; const contentBgX = Math.max(0, Math.min(width - contentBgW, contentVisualCenter - contentBgW / 2)); const contentBgRight = contentBgX + contentBgW; const contentBgY = contentBgInsetY; const contentBgBottom = height - contentBgInsetY;
svg.append("rect") .attr("class", "hdbar01-background") .attr("x", contentBgX) .attr("y", contentBgY) .attr("width", contentBgRight - contentBgX) .attr("height", contentBgBottom - contentBgY) .attr("fill", "#ffffff") .attr("opacity", 0.62);
const panelClipId = "hdbar01-panel-clip"; defs.append("clipPath") .attr("id", panelClipId) .append("rect") .attr("x", tableX) .attr("y", tableY) .attr("width", tableW) .attr("height", tableH) .attr("rx", panelRadius) .attr("ry", panelRadius);
svg.append("rect") .attr("class", "hdbar01-table-panel") .attr("data-role", "chart-table-panel") .attr("x", tableX) .attr("y", tableY) .attr("width", tableW) .attr("height", tableH) .attr("rx", panelRadius) .attr("fill", "#ffffff") .attr("filter", "url(#hdbar01-panel-shadow)");
const table = svg.append("g") .attr("class", "hdbar01-table") .attr("clip-path", `url(#${panelClipId})`);
table.append("rect") .attr("class", "hdbar01-header") .attr("x", tableX) .attr("y", tableY) .attr("width", tableW) .attr("height", headerH) .attr("fill", "url(#hdbar01-header-gradient)");
table.append("line") .attr("class", "hdbar01-column-divider") .attr("x1", dividerX) .attr("y1", tableY) .attr("x2", dividerX) .attr("y2", tableY + tableH) .attr("stroke", "#d7e9f2") .attr("stroke-width", 1.4);
const headerFont = Math.max(10, Math.min(15, headerH * 0.28)); table.append("text") .attr("class", "hdbar01-column-title method-title") .attr("x", tableX + methodW / 2) .attr("y", tableY + headerH / 2) .attr("dy", "0.35em") .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", `${headerFont}px`) .style("font-weight", 800) .style("letter-spacing", "0px") .style("fill", "#ffffff") .text(formatHeaderName(dimensionChannel.name || dimensionField).toUpperCase());
const valueHeader = `${formatHeaderName(valueChannel.name || valueField).toUpperCase()}${valueUnit ? ` (${valueUnit})` : ""}`; const headerLines = wrapWords(valueHeader, Math.max(13, Math.floor((tableW - methodW - 24) / (headerFont * 0.58))), 2); const headerText = table.append("text") .attr("class", "hdbar01-column-title value-title") .attr("x", dividerX + (tableW - methodW) / 2) .attr("y", tableY + headerH / 2 - (headerLines.length - 1) * headerFont * 0.45) .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", `${headerFont}px`) .style("font-weight", 800) .style("letter-spacing", "0px") .style("fill", "#ffffff"); headerLines.forEach((line, i) => { headerText.append("tspan") .attr("x", dividerX + (tableW - methodW) / 2) .attr("dy", i === 0 ? "0.35em" : `${headerFont * 1.1}px`) .text(line); });
rows.forEach((d, rowIndex) => { const y0 = bodyY + rowIndex * rowH; const cy = y0 + rowH / 2; const slotColor = severityColor(d.value, minValue, maxValue); const row = table.append("g") .attr("class", "hdbar01-row") .attr("data-row-index", rowIndex) .attr("data-category", d.label) .attr("data-value", d.value);
if (rowIndex > 0) { row.append("line") .attr("class", "hdbar01-row-separator") .attr("x1", tableX) .attr("y1", y0) .attr("x2", tableX + tableW) .attr("y2", y0) .attr("stroke", "#d7e9f2") .attr("stroke-width", 1); }
row.append("circle") .attr("class", "reserved-asset-slot hdbar01-row-icon-slot") .attr("data-asset-slot", "row-icon") .attr("data-category", d.label) .attr("cx", iconX) .attr("cy", cy) .attr("r", iconR) .attr("fill", tint(slotColor, 0.86)) .attr("stroke", tint(slotColor, 0.58)) .attr("stroke-width", 1.1);
row.append("circle") .attr("class", "hdbar01-neutral-row-icon-mark") .attr("cx", iconX) .attr("cy", cy) .attr("r", Math.max(2.6, iconR * 0.22)) .attr("fill", slotColor) .attr("opacity", 0.82);
const labelLines = wrapMeasured(row, d.label, labelW, labelFont, typography.label.font_family, 700, Math.max(1, Math.min(2, Math.floor(rowH / (labelFont * 1.08))))); const label = row.append("text") .attr("class", "hdbar01-method-label") .attr("x", labelX) .attr("y", cy - (labelLines.length - 1) * labelFont * 0.52) .attr("text-anchor", "start") .style("font-family", typography.label.font_family) .style("font-size", `${labelFont}px`) .style("font-weight", 700) .style("fill", textColor); labelLines.forEach((line, i) => { label.append("tspan") .attr("x", labelX) .attr("dy", i === 0 ? "0.35em" : `${labelFont * 1.1}px`) .text(line); });
row.append("rect") .attr("class", "hdbar01-bar-track") .attr("x", barStart) .attr("y", cy - trackH / 2) .attr("width", barMaxW) .attr("height", trackH) .attr("rx", trackH * 0.42) .attr("fill", "#eaf3f7");
row.append("line") .attr("class", "hdbar01-zero-axis-tick") .attr("x1", barZeroX) .attr("y1", cy - trackH * 0.78) .attr("x2", barZeroX) .attr("y2", cy + trackH * 0.78) .attr("stroke", "#9eb7c5") .attr("stroke-width", 1) .attr("opacity", 0.65);
const isNegative = d.value < 0; const sideSpan = isNegative ? negativeSpan : positiveSpan; const sideMax = isNegative ? negativeMax : positiveMax; const barRatio = sideMax > 0 ? Math.min(1, Math.abs(d.value) / sideMax) : 0; const renderedBarW = Math.max( Math.max(4, sideSpan * 0.04), barRatio * sideSpan ); const barX = isNegative ? barZeroX - renderedBarW : barZeroX;
row.append("rect") .attr("class", "hdbar01-emissions-bar") .attr("data-role", "bar") .attr("data-category", d.label) .attr("data-value", d.value) .attr("x", barX) .attr("y", cy - trackH / 2) .attr("width", renderedBarW) .attr("height", trackH) .attr("rx", trackH * 0.36) .attr("fill", slotColor);
const labelGap = Math.max(8, tableW * 0.015); const preferredValueX = barX + renderedBarW + labelGap; const valueX = Math.min(preferredValueX, valueAreaRight - maxValueTextWidth * 0.52); const formatted = `${d.value >= 0 ? "+" : ""}${chartUtils.format.autoText(d.value)}`; const valueText = row.append("text") .attr("class", "hdbar01-value-label") .attr("data-role", "value-label") .attr("x", valueX) .attr("y", cy) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${valueFont}px`) .style("font-weight", 800) .style("fill", "#071f45"); valueText.append("tspan").text(formatted); if (valueUnit) { valueText.append("tspan") .attr("dx", Math.max(3, valueFont * 0.2)) .style("font-size", `${unitFont}px`) .style("font-weight", 700) .style("fill", "#183153") .text(valueUnit); } });
const cueLabelFont = Math.max(8, Math.min(11, rowH * 0.18)); const cueTop = bodyY + Math.max(cueEndpointR + cueLabelFont * 2.8 + 14, rowH * 0.58); const cueBottom = bodyY + bodyH - Math.max(cueEndpointR + cueLabelFont * 2.8 + 14, rowH * 0.72); const cue = svg.append("g") .attr("class", "hdbar01-emissions-cue") .attr("data-role", "low-high-emissions-cue");
cue.append("circle") .attr("class", "reserved-asset-slot hdbar01-cue-endpoint-slot low") .attr("data-asset-slot", "emissions-cue-endpoint") .attr("data-endpoint", "low") .attr("cx", cueX) .attr("cy", cueTop) .attr("r", cueEndpointR) .attr("fill", "#f8fff9") .attr("stroke", "#15964f") .attr("stroke-width", 2);
cue.append("circle") .attr("cx", cueX) .attr("cy", cueTop) .attr("r", 4) .attr("fill", "#15964f") .attr("opacity", 0.72);
const cueStroke = Math.max(4, width * 0.008); const cueLineTop = cueTop + cueEndpointR + 14; const cueLineBottom = cueBottom - cueEndpointR - 14; const cueLineMid1 = cueLineTop + (cueLineBottom - cueLineTop) * 0.36; const cueLineMid2 = cueLineTop + (cueLineBottom - cueLineTop) * 0.64; [ [cueLineTop, cueLineMid1, cueLowColor], [cueLineMid1, cueLineMid2, cueMidColor], [cueLineMid2, cueLineBottom, cueHighColor] ].forEach(([y1, y2, stroke], index) => { cue.append("line") .attr("class", "hdbar01-cue-shaft") .attr("data-cue-segment", index) .attr("x1", cueX) .attr("y1", y1) .attr("x2", cueX) .attr("y2", y2) .attr("stroke", stroke) .attr("stroke-width", cueStroke) .attr("stroke-linecap", "round"); });
cue.append("path") .attr("class", "hdbar01-cue-arrowhead top") .attr("d", `M ${cueX - 9},${cueLineTop + 10} L ${cueX + 9},${cueLineTop + 10} L ${cueX},${cueLineTop - 6} Z`) .attr("fill", cueLowColor);
cue.append("path") .attr("class", "hdbar01-cue-arrowhead bottom") .attr("d", `M ${cueX - 9},${cueLineBottom - 10} L ${cueX + 9},${cueLineBottom - 10} L ${cueX},${cueLineBottom + 6} Z`) .attr("fill", cueHighColor);
cue.append("circle") .attr("class", "reserved-asset-slot hdbar01-cue-endpoint-slot high") .attr("data-asset-slot", "emissions-cue-endpoint") .attr("data-endpoint", "high") .attr("cx", cueX) .attr("cy", cueBottom) .attr("r", cueEndpointR) .attr("fill", "#fffafa") .attr("stroke", "#cf2824") .attr("stroke-width", 2);
cue.append("circle") .attr("cx", cueX) .attr("cy", cueBottom) .attr("r", 4) .attr("fill", "#cf2824") .attr("opacity", 0.72);
const cueMetric = compactCueMetric(valueChannel.name || valueField); addCueLabel(cue, "LOWEST", cueMetric, cueX, cueTop - cueEndpointR - cueLabelFont * 1.55, "#15814a", typography.label.font_family, cueLabelFont); addCueLabel(cue, "HIGHEST", cueMetric, cueX, cueBottom + cueEndpointR + cueLabelFont * 1.05, "#c62421", typography.label.font_family, cueLabelFont);
return svg.node();
function addCueLabel(parent, line1, line2, x, y, fill, fontFamily, fontSize) { const text = parent.append("text") .attr("class", "hdbar01-cue-label") .attr("x", x) .attr("y", y) .attr("text-anchor", "middle") .style("font-family", fontFamily) .style("font-size", `${fontSize}px`) .style("font-weight", 800) .style("fill", fill); text.append("tspan").attr("x", x).text(line1); text.append("tspan").attr("x", x).attr("dy", `${fontSize * 1.12}px`).text(line2); }
function wrapWords(text, maxChars, maxLines) { const words = String(text).split(/\s+/).filter(Boolean); const lines = []; let current = ""; words.forEach(word => { const next = current ? `${current} ${word}` : word; if (next.length <= maxChars || !current) { current = next; } else { lines.push(current); current = word; } }); if (current) lines.push(current); if (lines.length > maxLines) { const trimmed = lines.slice(0, maxLines); trimmed[maxLines - 1] = `${trimmed[maxLines - 1].replace(/\.*$/, "")}...`; return trimmed; } return lines; }
function formatHeaderName(value) { return String(value) .replace(/[_-]+/g, " ") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/\s+/g, " ") .trim(); }
function compactCueMetric(value) { const cleaned = formatHeaderName(value) .replace(/\([^)]*\)/g, " ") .replace(/\b(intensity|rate|score|index|percent|percentage|amount|total|average|avg|value)\b/gi, " ") .replace(/\s+/g, " ") .trim(); if (/emission/i.test(value)) return "EMISSIONS"; if (/deficit/i.test(value)) return "DEFICIT"; if (/surplus/i.test(value)) return "SURPLUS"; if (/change/i.test(value)) return "CHANGE"; if (/sales/i.test(value)) return "SALES"; const words = cleaned.split(/\s+/).filter(Boolean); return (words[0] || "VALUE").toUpperCase(); }
function wrapMeasured(parent, text, maxWidth, fontSize, fontFamily, fontWeight, maxLines) { const words = String(text).split(/\s+/).filter(Boolean); const lines = []; let current = ""; words.forEach(word => { const next = current ? `${current} ${word}` : word; const nextWidth = chartUtils.text.measure(parent, next, { fontFamily, fontSize, fontWeight }).width; if (nextWidth <= maxWidth || !current) { current = next; } else { lines.push(current); current = word; } }); if (current) lines.push(current); if (lines.length > maxLines) { const trimmed = lines.slice(0, maxLines); let last = trimmed[maxLines - 1]; while (last.length > 4 && chartUtils.text.measure(parent, `${last}...`, { fontFamily, fontSize, fontWeight }).width > maxWidth) { last = last.replace(/\s*\S+$/, ""); } trimmed[maxLines - 1] = `${(last || String(text).slice(0, 8)).trim()}...`; return trimmed; } return lines; }
function severityColor(value, minValue, maxValue) { if (value < 0) { const negativeFloor = Math.min(0, minValue); const t = Math.max(0, Math.min(1, (value - negativeFloor) / Math.max(1e-6, -negativeFloor))); return interpolateColorStops(t, [ [0.00, cueLowColor], [1.00, cueMidColor] ]); }
const positiveCeiling = Math.max(0, maxValue); const t = Math.max(0, Math.min(1, value / Math.max(1e-6, positiveCeiling))); return interpolateColorStops(t, [ [0.00, cueMidColor], [1.00, cueHighColor] ]); }
function interpolateColorStops(t, stops) { for (let i = 1; i < stops.length; i++) { const [prevT, prevColor] = stops[i - 1]; const [nextT, nextColor] = stops[i]; if (t <= nextT) { const localT = (t - prevT) / Math.max(1e-6, nextT - prevT); return d3.interpolateRgb(prevColor, nextColor)(Math.max(0, Math.min(1, localT))); } } return stops[stops.length - 1][1]; }
function tint(hex, amount) { const c = d3.color(hex); if (!c) return hex; const r = Math.round(c.r + (255 - c.r) * amount); const g = Math.round(c.g + (255 - c.g) * amount); const b = Math.round(c.b + (255 - c.b) * amount); return `rgb(${r},${g},${b})`; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Diverging Bar Chart", "chart_name": "horizontal_diverging_bar_chart_01_hand", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 15], ["-inf", "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary","secondary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "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 jsonData = data; const rawData = (jsonData.data && jsonData.data.data) ? jsonData.data.data : []; const variables = jsonData.variables || {}; 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" } }; const colorResolver = chartUtils.color.resolver(jsonData);
d3.select(containerSelector).html("");
const width = variables.width || 600; const height = variables.height || 600;
const dimensionChannel = chartUtils.schema.channel(jsonData, "x", { fallbackKey: "dimension" }); const valueChannel = chartUtils.schema.channel(jsonData, "y", { fallbackKey: "value" }); const dimensionField = dimensionChannel.key; const valueField = valueChannel.key; const valueUnit = valueChannel.unit || ""; const rows = rawData .map((d, index) => ({ raw: d, index, label: String(d[dimensionField]), value: +d[valueField] })) .filter(d => Number.isFinite(d.value)) .sort((a, b) => a.value - b.value);
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("data-chart", "horizontal_diverging_bar_chart_01_hand") .attr("data-reference-style", "news-bias-diverging-panel");
const defs = svg.append("defs");
const panelClipId = "hdbar01hand-panel-clip"; const plotClipId = "hdbar01hand-plot-clip"; const panelX = Math.max(18, width * 0.045); const panelY = Math.max(10, height * 0.02); const panelW = width - panelX * 2; const panelH = height - panelY * 2; const tabY = panelY + Math.max(8, panelH * 0.028); const tabH = Math.max(18, Math.min(28, panelH * 0.047)); const chipH = Math.max(58, Math.min(76, panelH * 0.13)); const chipY = panelY + panelH - chipH - Math.max(16, panelH * 0.03); const plotTop = tabY + tabH + Math.max(16, panelH * 0.035); const plotBottom = chipY - Math.max(20, panelH * 0.035); const plotH = Math.max(120, plotBottom - plotTop); const iconX = panelX + Math.max(22, panelW * 0.055); const labelX = iconX + Math.max(19, panelW * 0.044); const labelW = Math.max(78, panelW * 0.235); const plotX0 = labelX + labelW + Math.max(18, panelW * 0.035); const plotX1 = panelX + panelW - Math.max(44, panelW * 0.07); const valueLabelReserve = Math.max(58, Math.min(86, panelW * 0.13)); const scaleX0 = plotX0 + valueLabelReserve; const scaleX1 = plotX1 - valueLabelReserve; const zeroX = scaleX0 + (scaleX1 - scaleX0) * 0.5; const maxAbs = Math.max(1e-6, d3.max(rows, d => Math.abs(d.value)) || 1); const xScale = d3.scaleLinear() .domain([-maxAbs, maxAbs]) .range([scaleX0, scaleX1]); const yScale = d3.scaleBand() .domain(rows.map(d => d.label)) .range([plotTop, plotTop + plotH]) .padding(rows.length > 12 ? 0.18 : 0.24); const rowH = Math.max(1, yScale.bandwidth()); const barH = Math.max(5, Math.min(18, rowH * 0.52)); const labelFont = Math.max(7.5, Math.min(11, rowH * 0.38)); const valueFont = Math.max(7.5, Math.min(10.5, rowH * 0.38)); const textColor = colorResolver.text({ fallback: "#11223f" }).value || "#11223f"; const leftColor = "#0B5CA8"; const rightColor = "#E3322B";
defs.append("clipPath") .attr("id", panelClipId) .append("rect") .attr("x", panelX) .attr("y", panelY) .attr("width", panelW) .attr("height", panelH) .attr("rx", 2);
defs.append("clipPath") .attr("id", plotClipId) .append("rect") .attr("x", panelX + 4) .attr("y", plotTop - 7) .attr("width", panelW - 8) .attr("height", plotH + 14);
svg.append("rect") .attr("class", "hdbar01hand-page") .attr("x", 0) .attr("y", 0) .attr("width", width) .attr("height", height) .attr("fill", "#FFFFFF");
svg.append("rect") .attr("class", "hdbar01hand-panel") .attr("data-role", "chart-panel") .attr("x", panelX) .attr("y", panelY) .attr("width", panelW) .attr("height", panelH) .attr("rx", 2) .attr("fill", "#FFFFFF") .attr("stroke", "#FFFFFF") .attr("stroke-width", 0);
if (!rows.length) { svg.append("text") .attr("x", width / 2) .attr("y", height / 2) .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", "18px") .style("fill", textColor) .text("No data"); return svg.node(); }
const chart = svg.append("g") .attr("class", "hdbar01hand-chart") .attr("clip-path", `url(#${panelClipId})`);
const tabOuterPad = Math.max(10, panelW * 0.018); const leftTabX = panelX + tabOuterPad; const rightTabEdge = panelX + panelW - tabOuterPad; addTab(chart, leftTabX, tabY, zeroX - leftTabX - 2, tabH, leftColor, "<- LEFT-LEANING"); addTab(chart, zeroX + 2, tabY, rightTabEdge - zeroX - 2, tabH, rightColor, "RIGHT-LEANING ->");
chart.append("text") .attr("class", "hdbar01hand-zero-label") .attr("x", zeroX) .attr("y", tabY + tabH + 12) .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.max(7, valueFont * 0.92)}px`) .style("font-weight", 800) .style("fill", "#343F52") .text("0");
const ticks = xScale.ticks(5).filter(t => Math.abs(t) <= maxAbs + 1e-9); ticks.forEach(t => { const x = xScale(t); chart.append("line") .attr("class", "hdbar01hand-gridline") .attr("x1", x) .attr("x2", x) .attr("y1", plotTop - 6) .attr("y2", plotTop + plotH + 4) .attr("stroke", Math.abs(t) < 1e-9 ? "#536071" : "#E7ECF3") .attr("stroke-width", Math.abs(t) < 1e-9 ? 1.2 : 0.8); chart.append("text") .attr("class", "hdbar01hand-tick-label") .attr("x", x) .attr("y", plotTop + plotH + 15) .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.max(6.5, valueFont * 0.78)}px`) .style("fill", "#657083") .text(formatTick(t)); });
const rowLayer = chart.append("g") .attr("class", "hdbar01hand-row-layer") .attr("clip-path", `url(#${plotClipId})`);
rows.forEach((d, rowIndex) => { const cy = yScale(d.label) + rowH / 2; const barColor = d.value < 0 ? leftColor : rightColor; const x0 = xScale(0); const x1 = xScale(d.value); const barX = Math.min(x0, x1); const barW = Math.max(1.5, Math.abs(x1 - x0)); const row = rowLayer.append("g") .attr("class", "hdbar01hand-row") .attr("data-row-index", rowIndex) .attr("data-category", d.label) .attr("data-value", d.value);
row.append("line") .attr("class", "hdbar01hand-row-guide") .attr("x1", panelX + 10) .attr("x2", panelX + panelW - 10) .attr("y1", cy) .attr("y2", cy) .attr("stroke", "#EEF2F6") .attr("stroke-width", 0.8);
row.append("circle") .attr("class", "reserved-asset-slot hdbar01hand-row-source-logo-slot") .attr("data-asset-slot", "row-source-logo") .attr("data-category", d.label) .attr("data-anchor", "row-centerline-left-label-column") .attr("data-collision-rule", "stay-left-of-category-label-and-inside-panel") .attr("data-slot-policy", "retrieval_or_image2_asset") .attr("cx", iconX) .attr("cy", cy) .attr("r", Math.max(5, Math.min(9, rowH * 0.30))) .attr("fill", tint(barColor, 0.82)) .attr("stroke", barColor) .attr("stroke-width", 0.9);
row.append("text") .attr("class", "hdbar01hand-row-logo-placeholder") .attr("x", iconX) .attr("y", cy) .attr("dy", "0.32em") .attr("text-anchor", "middle") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.max(5.5, rowH * 0.22)}px`) .style("font-weight", 800) .style("fill", barColor) .text(abbrev(d.label));
const labelLines = wrapMeasured(row, d.label, labelW, labelFont, typography.label.font_family, 700, rowH < 18 ? 1 : 2); const label = row.append("text") .attr("class", "hdbar01hand-category-label") .attr("x", labelX) .attr("y", cy - (labelLines.length - 1) * labelFont * 0.52) .attr("text-anchor", "start") .style("font-family", typography.label.font_family) .style("font-size", `${labelFont}px`) .style("font-weight", 700) .style("fill", textColor); labelLines.forEach((line, i) => { label.append("tspan") .attr("x", labelX) .attr("dy", i === 0 ? "0.35em" : `${labelFont * 1.05}px`) .text(line); });
row.append("rect") .attr("class", "hdbar01hand-bar") .attr("data-role", "bar") .attr("data-category", d.label) .attr("data-value", d.value) .attr("x", barX) .attr("y", cy - barH / 2) .attr("width", barW) .attr("height", barH) .attr("rx", Math.min(4, barH * 0.35)) .attr("fill", barColor);
const formatted = `${d.value >= 0 ? "+" : ""}${chartUtils.format.autoText(d.value)}${valueUnit}`; const labelGap = Math.max(4, panelW * 0.008); const estimatedTextW = formatted.length * valueFont * 0.58; let valueX; let anchor; if (d.value < 0) { valueX = Math.max(plotX0 + 2, barX - labelGap); anchor = "end"; if (valueX - estimatedTextW < plotX0 + 2) { valueX = plotX0 + 2; anchor = "start"; } } else { valueX = Math.min(plotX1 - 2, barX + barW + labelGap); anchor = "start"; if (valueX + estimatedTextW > plotX1 - 2) { valueX = plotX1 - 2; anchor = "end"; } } row.append("text") .attr("class", "hdbar01hand-value-label") .attr("data-role", "value-label") .attr("x", valueX) .attr("y", cy) .attr("dy", "0.35em") .attr("text-anchor", anchor) .style("font-family", typography.annotation.font_family) .style("font-size", `${valueFont}px`) .style("font-weight", 800) .style("fill", barColor) .text(formatted); });
const chipLayer = chart.append("g") .attr("class", "hdbar01hand-classification-chips") .attr("data-role", "bottom-classification-chips"); const chipGap = Math.max(8, panelW * 0.018); const chipW = (panelW - chipGap * 4) / 3; const chips = [ { title: "Left-Leaning", body: "negative signed scores", color: leftColor }, { title: "Center", body: "near the zero line", color: "#58667A" }, { title: "Right-Leaning", body: "positive signed scores", color: rightColor } ]; chips.forEach((chip, i) => { const x = panelX + chipGap + i * (chipW + chipGap); const g = chipLayer.append("g") .attr("class", "hdbar01hand-chip") .attr("data-chip", chip.title.toLowerCase().replace(/[^a-z]+/g, "-")); g.append("rect") .attr("x", x) .attr("y", chipY) .attr("width", chipW) .attr("height", chipH) .attr("rx", 8) .attr("fill", tint(chip.color, 0.92)) .attr("stroke", tint(chip.color, 0.52)) .attr("stroke-width", 1); g.append("circle") .attr("class", "reserved-asset-slot hdbar01hand-chip-icon-slot") .attr("data-asset-slot", "classification-chip-icon") .attr("data-anchor", "chip-left-centerline") .attr("data-collision-rule", "stay-inside-chip-and-left-of-chip-text") .attr("data-slot-policy", "neutral_placeholder") .attr("cx", x + Math.max(14, chipW * 0.13)) .attr("cy", chipY + chipH / 2) .attr("r", Math.max(7, Math.min(10, chipH * 0.16))) .attr("fill", chip.color); g.append("text") .attr("x", x + Math.max(31, chipW * 0.26)) .attr("y", chipY + chipH * 0.42) .attr("text-anchor", "start") .style("font-family", typography.label.font_family) .style("font-size", `${Math.max(8.5, Math.min(11, chipW * 0.072))}px`) .style("font-weight", 800) .style("fill", "#182338") .text(chip.title); g.append("text") .attr("x", x + Math.max(31, chipW * 0.26)) .attr("y", chipY + chipH * 0.68) .attr("text-anchor", "start") .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.max(6.8, Math.min(8.5, chipW * 0.058))}px`) .style("font-weight", 600) .style("fill", "#526071") .text(chip.body); });
return svg.node();
function addTab(parent, x, y, w, h, fill, label) { parent.append("rect") .attr("class", "hdbar01hand-direction-tab") .attr("data-role", "direction-tab") .attr("x", x) .attr("y", y) .attr("width", Math.max(1, w)) .attr("height", h) .attr("rx", 4) .attr("fill", fill); parent.append("text") .attr("class", "hdbar01hand-direction-tab-label") .attr("x", x + w / 2) .attr("y", y + h / 2) .attr("dy", "0.34em") .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", `${Math.max(8, Math.min(11, h * 0.42))}px`) .style("font-weight", 800) .style("fill", "#FFFFFF") .text(label); }
function wrapMeasured(parent, text, maxWidth, fontSize, fontFamily, fontWeight, maxLines) { const words = String(text).split(/\s+/).filter(Boolean); const lines = []; let current = ""; words.forEach(word => { const next = current ? `${current} ${word}` : word; const nextWidth = chartUtils.text.measure(parent, next, { fontFamily, fontSize, fontWeight }).width; if (nextWidth <= maxWidth || !current) { current = next; } else { lines.push(current); current = word; } }); if (current) lines.push(current); if (lines.length > maxLines) { const trimmed = lines.slice(0, maxLines); let last = trimmed[maxLines - 1]; while (last.length > 3 && chartUtils.text.measure(parent, `${last}...`, { fontFamily, fontSize, fontWeight }).width > maxWidth) { last = last.replace(/\s*\S+$/, ""); } trimmed[maxLines - 1] = `${(last || String(text).slice(0, 8)).trim()}...`; return trimmed; } return lines; }
function formatTick(value) { if (Math.abs(value) < 1e-9) return "0"; return `${value > 0 ? "+" : ""}${chartUtils.format.autoText(value)}`; }
function abbrev(label) { return String(label) .split(/\s+/) .filter(Boolean) .slice(0, 2) .map(d => d.charAt(0).toUpperCase()) .join("") .slice(0, 2) || "S"; }
function tint(hex, amount) { const c = d3.color(hex); if (!c) return hex; const r = Math.round(c.r + (255 - c.r) * amount); const g = Math.round(c.g + (255 - c.g) * amount); const b = Math.round(c.b + (255 - c.b) * amount); return `rgb(${r},${g},${b})`; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Diverging Bar Chart", "chart_name": "horizontal_diverging_bar_chart_02", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 20], ["-inf", "inf"]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["positive", "negative"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const colorResolver = chartUtils.color.resolver(data); const jsonData = data; const sourceRows = (jsonData.data && jsonData.data.data) ? jsonData.data.data : []; const variables = jsonData.variables || {}; const metadata = jsonData.metadata || {}; const xChannel = chartUtils.schema.channel(jsonData, "x", { fallbackKey: "category" }); const yChannel = chartUtils.schema.channel(jsonData, "y", { fallbackKey: "value" }); const categoryField = xChannel.key; const valueField = yChannel.key; const unit = yChannel.unit || "";
const baseWidth = variables.width || 1024; const baseHeight = variables.height || 1536; const width = 1024; const height = 1536; const svg = d3.select(containerSelector) .html("") .append("svg") .attr("width", baseWidth) .attr("height", baseHeight) .attr("viewBox", `0 0 ${width} ${height}`) .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink") .attr("data-chart-variation", "horizontal_diverging_bar_chart_02");
const colors = { navy: "#0a1f46", navy2: "#12346e", muted: "#34435a", lightText: "#637085", grid: "#d2dae2", gridDark: "#8b98a7", green: "#177f42", greenDark: "#0d6f35", greenSoft: "#eef8f1", red: "#ef3d39", redDark: "#d7191c", redSoft: "#fff3f1", paper: "#f8faf8", panel: "#ffffff" };
svg.append("rect") .attr("width", width) .attr("height", height) .attr("fill", colors.paper);
const defs = svg.append("defs"); const softShadow = defs.append("filter") .attr("id", "hdb02-soft-shadow") .attr("x", "-20%") .attr("y", "-20%") .attr("width", "140%") .attr("height", "140%"); softShadow.append("feDropShadow") .attr("dx", "0") .attr("dy", "8") .attr("stdDeviation", "10") .attr("flood-color", "#0b1f46") .attr("flood-opacity", "0.10");
const positiveGradient = defs.append("linearGradient") .attr("id", "hdb02-positive-gradient") .attr("x1", "0%") .attr("x2", "100%") .attr("y1", "0%") .attr("y2", "0%"); positiveGradient.append("stop").attr("offset", "0%").attr("stop-color", "#106f45"); positiveGradient.append("stop").attr("offset", "100%").attr("stop-color", "#1b9159");
const negativeGradient = defs.append("linearGradient") .attr("id", "hdb02-negative-gradient") .attr("x1", "100%") .attr("x2", "0%") .attr("y1", "0%") .attr("y2", "0%"); negativeGradient.append("stop").attr("offset", "0%").attr("stop-color", "#ff5b55"); negativeGradient.append("stop").attr("offset", "100%").attr("stop-color", "#d60f12");
function temporalKeyFor(value) { const text = String(value == null ? "" : value).trim(); const lower = text.toLowerCase(); const monthIndex = { jan: 0, january: 0, feb: 1, february: 1, mar: 2, march: 2, apr: 3, april: 3, may: 4, jun: 5, june: 5, jul: 6, july: 6, aug: 7, august: 7, sep: 8, sept: 8, september: 8, oct: 9, october: 9, nov: 10, november: 10, dec: 11, december: 11 }; const seasonIndex = { winter: 0, spring: 1, summer: 2, fall: 3, autumn: 3 };
let m = lower.match(/^(\d{4})[-/.](\d{1,2})(?:[-/.](\d{1,2}))?$/); if (m) { return Number(m[1]) * 400 + (Number(m[2]) - 1) * 31 + Number(m[3] || 1); } m = lower.match(/^(\d{4})\s*q([1-4])$/) || lower.match(/^q([1-4])\s*(\d{4})$/); if (m) { const year = m[2] && m[2].length === 4 ? Number(m[2]) : Number(m[1]); const quarter = m[2] && m[2].length === 4 ? Number(m[1]) : Number(m[2]); return year * 400 + (quarter - 1) * 90; } m = lower.match(/^([a-z]+)\s+(\d{4})$/) || lower.match(/^(\d{4})\s+([a-z]+)$/); if (m) { const year = /^\d{4}$/.test(m[1]) ? Number(m[1]) : Number(m[2]); const word = /^\d{4}$/.test(m[1]) ? m[2] : m[1]; if (Object.prototype.hasOwnProperty.call(monthIndex, word)) return year * 400 + monthIndex[word] * 31; if (Object.prototype.hasOwnProperty.call(seasonIndex, word)) return year * 400 + seasonIndex[word] * 90; } if (Object.prototype.hasOwnProperty.call(monthIndex, lower)) return 2000 * 400 + monthIndex[lower] * 31; if (Object.prototype.hasOwnProperty.call(seasonIndex, lower)) return 2000 * 400 + seasonIndex[lower] * 90; m = lower.match(/^(\d{4})$/); if (m) return Number(m[1]) * 400; return null; }
function fieldNameLooksTemporal(name) { return /(^|[_\s-])(year|date|month|quarter|season|timestamp|time|week|day|period)(s)?($|[_\s-])/i.test(String(name || "")); }
const rows = sourceRows .map((d, index) => ({ raw: d, index, category: String(d[categoryField] == null ? `Item ${index + 1}` : d[categoryField]), value: +d[valueField], temporalKey: temporalKeyFor(d[categoryField]) })) .filter(d => Number.isFinite(d.value)); const temporalHitCount = rows.filter(d => d.temporalKey !== null).length; const usesTemporalOrder = rows.length > 1 && ( temporalHitCount >= Math.max(2, Math.ceil(rows.length * 0.6)) || (fieldNameLooksTemporal(categoryField) && temporalHitCount > 0) ); svg.attr("data-row-ordering", usesTemporalOrder ? "chronological" : "diverging-value-groups"); const positives = rows.filter(d => d.value >= 0).sort((a, b) => b.value - a.value); const negatives = rows.filter(d => d.value < 0).sort((a, b) => b.value - a.value); const orderedRows = usesTemporalOrder ? rows.slice().sort((a, b) => (a.temporalKey - b.temporalKey) || (a.index - b.index)) : positives.concat(negatives);
function splitWords(text, maxChars, maxLines) { const words = String(text || "").replace(/\s+/g, " ").trim().split(" ").filter(Boolean); const lines = []; let current = ""; words.forEach(word => { const test = current ? `${current} ${word}` : word; if (test.length <= maxChars || !current) { current = test; } else { lines.push(current); current = word; } }); if (current) lines.push(current); if (maxLines && lines.length > maxLines) { const kept = lines.slice(0, maxLines); kept[maxLines - 1] = kept[maxLines - 1].replace(/\.*$/, "") + "..."; return kept; } return lines; }
function addWrappedText(parent, text, x, y, options) { const lineHeight = options.lineHeight || options.fontSize * 1.18; const lines = splitWords(text, options.maxChars || 48, options.maxLines || 3); const textNode = parent.append("text") .attr("x", x) .attr("y", y) .attr("text-anchor", options.anchor || "start") .style("font-family", options.fontFamily || "Arial, Helvetica, sans-serif") .style("font-size", `${options.fontSize}px`) .style("font-weight", options.fontWeight || 400) .style("letter-spacing", options.letterSpacing || 0) .style("fill", options.fill || colors.navy); lines.forEach((line, i) => { textNode.append("tspan") .attr("x", x) .attr("dy", i === 0 ? 0 : lineHeight) .text(line); }); return { node: textNode, lines, height: lines.length * lineHeight }; }
function valueFmt(value) { const abs = Math.abs(value); const decimals = abs >= 20 ? 1 : (abs >= 1 ? 1 : 2); let out = chartUtils.format.autoText ? chartUtils.format.autoText(value) : value.toFixed(decimals); if (String(out).indexOf(".") >= 0) out = String(out).replace(/\.0+$/, "").replace(/(\.\d*[1-9])0+$/, "$1"); return `${value > 0 ? "+" : ""}${out}`; }
function metricLabel() { if (unit === "$b" || unit === "$B") return "BILLION USD"; if (unit) return unit.toUpperCase(); return String(valueField || "value").replace(/([a-z])([A-Z])/g, "$1 $2").toUpperCase(); }
function axisFmt(value) { if (Math.abs(value) >= 1000) return chartUtils.format.autoText(value); if (Math.abs(value) < 1 && value !== 0) return value.toFixed(1).replace(/\.0$/, ""); return String(Math.round(value * 10) / 10).replace(/\.0$/, ""); }
function niceStep(maxAbs) { if (maxAbs > 200) return 50; if (maxAbs > 80) return 20; if (maxAbs > 20) return 10; if (maxAbs > 5) return 2; if (maxAbs > 1) return 0.5; return 0.2; }
const minValue = d3.min(rows, d => d.value) || 0; const maxValue = d3.max(rows, d => d.value) || 0; const step = niceStep(Math.max(Math.abs(minValue), Math.abs(maxValue))); let domainMin = minValue < 0 ? Math.floor((minValue * 1.10) / step) * step : 0; let domainMax = maxValue > 0 ? Math.ceil((maxValue * 1.60) / step) * step : 0; if (domainMin === 0 && domainMax === 0) { domainMin = -1; domainMax = 1; } else if (domainMin === 0) { domainMin = -step; } else if (domainMax === 0) { domainMax = step; } if (maxValue > 0 && minValue < 0 && Math.abs(domainMin) < domainMax * 0.35) { domainMin = -domainMax * 0.35; } else if (maxValue > 0 && minValue >= 0) { domainMin = -domainMax * 0.25; }
const x0 = 180; const x1 = 910; const xScale = d3.scaleLinear().domain([domainMin, domainMax]).range([x0, x1]); const zeroX = xScale(0); const axisY = 1396; const rowTop = 445; const chipHeight = 46; const chipGap = 22; const chipToRowGap = 26; const groupGap = !usesTemporalOrder && positives.length && negatives.length ? 28 : 0; const reservedForChips = usesTemporalOrder ? 0 : ( (positives.length ? chipHeight + chipToRowGap : 0) + (negatives.length ? chipHeight + chipToRowGap : 0) + groupGap ); const rowStep = Math.max(48, Math.min(84, (axisY - rowTop - reservedForChips - 16) / Math.max(orderedRows.length, 1))); const bandHeight = Math.max(34, rowStep * 0.72); const barHeight = Math.max(18, bandHeight * 0.58); const labelFont = Math.max(17, Math.min(24, rowStep * 0.30)); const valueFont = Math.max(17, Math.min(30, rowStep * 0.36));
const title = metadata.title || jsonData.title || ""; const titleParts = String(title).split(":"); const eyebrow = titleParts.length > 1 ? `${titleParts[0].trim()}:` : ""; const mainTitle = (titleParts.length > 1 ? titleParts.slice(1).join(":") : title).trim(); const mainSegments = mainTitle.includes(",") ? mainTitle.split(",").map(s => s.trim()).filter(Boolean) : splitWords(mainTitle, 20, 3);
if (eyebrow) { svg.append("text") .attr("x", 52) .attr("y", 78) .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", "30px") .style("font-weight", 800) .style("letter-spacing", "3px") .style("fill", colors.navy) .text(eyebrow.toUpperCase()); }
const titleY = eyebrow ? 165 : 96; mainSegments.slice(0, 3).forEach((line, i) => { svg.append("text") .attr("x", 52) .attr("y", titleY + i * (mainSegments.length > 2 ? 58 : 70)) .style("font-family", "Arial Black, Arial, Helvetica, sans-serif") .style("font-size", mainSegments.length > 2 ? "48px" : "56px") .style("font-weight", 900) .style("letter-spacing", "0") .style("fill", i === 1 ? colors.green : colors.navy) .text(line.toUpperCase()); });
const subtitleText = metadata.description || jsonData.description || ""; addWrappedText(svg, subtitleText, 52, 323, { fontSize: 24, lineHeight: 34, maxChars: 64, maxLines: 3, fill: colors.navy, fontWeight: 400 });
const art = svg.append("g") .attr("class", "reserved-asset-slot header-trade-art-slot") .attr("data-asset-slot", "header-thematic-trade-art") .attr("data-slot-policy", "image2_asset_or_retrieval_owned") .attr("data-anchor", "top-right-header-safe-area") .attr("data-collision-rule", "stay-right-of-title-and-above-chart-rows") .attr("transform", "translate(764,48)"); art.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", 210) .attr("height", 180) .attr("rx", 28) .attr("fill", "#eef5f8") .attr("opacity", 0.82); art.append("circle").attr("cx", 112).attr("cy", 88).attr("r", 66).attr("fill", "#dbe8ef"); art.append("path") .attr("d", "M34,126 C78,96 140,154 186,104") .attr("fill", "none") .attr("stroke", "#8fb0c2") .attr("stroke-width", 8) .attr("stroke-linecap", "round") .attr("opacity", 0.55); art.append("rect") .attr("x", 34) .attr("y", 58) .attr("width", 64) .attr("height", 42) .attr("rx", 10) .attr("fill", "#d93b36") .attr("opacity", 0.88); art.append("rect") .attr("x", 128) .attr("y", 66) .attr("width", 66) .attr("height", 40) .attr("rx", 10) .attr("fill", "#12346e") .attr("opacity", 0.88); art.append("text") .attr("x", 108) .attr("y", 148) .attr("text-anchor", "middle") .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", "11px") .style("font-weight", 700) .style("fill", "#5c6d7c") .text("RESERVED ART SLOT");
svg.append("line") .attr("x1", 52) .attr("x2", 972) .attr("y1", 430) .attr("y2", 430) .attr("stroke", colors.grid) .attr("stroke-width", 2);
const chartMetric = metricLabel(); addWrappedText(svg, chartMetric.toUpperCase(), 810, 462, { fontSize: 17, lineHeight: 24, maxChars: 18, maxLines: 2, fill: colors.muted, fontWeight: 700, anchor: "middle" });
function sectionChip(y, type) { const isPositive = type === "positive"; const g = svg.append("g") .attr("class", `section-chip ${type}`) .attr("data-section", type); const x = 58; const desiredChipW = isPositive ? 500 : 520; const zeroLineGap = 26; const maxSafeChipW = Math.max(248, zeroX - x - zeroLineGap); const chipW = Math.min(desiredChipW, maxSafeChipW); const detailText = chipW >= 390 ? (isPositive ? "(positive balance)" : "(negative balance)") : ""; const detailX = x + (isPositive ? 210 : 190); g.append("rect") .attr("x", x) .attr("y", y) .attr("width", chipW) .attr("height", chipHeight) .attr("rx", chipHeight / 2) .attr("fill", isPositive ? "#e0f0df" : "#fde6e3"); g.append("circle") .attr("cx", x + 25) .attr("cy", y + chipHeight / 2) .attr("r", 24) .attr("fill", isPositive ? colors.green : colors.red); g.append("text") .attr("x", x + 25) .attr("y", y + chipHeight / 2 + 8) .attr("text-anchor", "middle") .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", "28px") .style("font-weight", 900) .style("fill", "#ffffff") .text(isPositive ? "↗" : "↘"); g.append("text") .attr("x", x + 82) .attr("y", y + 31) .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", "23px") .style("font-weight", 800) .style("fill", isPositive ? colors.greenDark : colors.redDark) .text(isPositive ? "SURPLUS" : "DEFICIT"); if (detailText) { g.append("text") .attr("x", detailX) .attr("y", y + 31) .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", "20px") .style("font-weight", 700) .style("fill", isPositive ? colors.greenDark : colors.redDark) .text(detailText); } }
const rowPositions = new Map(); let cursorY = rowTop; if (usesTemporalOrder) { orderedRows.forEach(row => { rowPositions.set(row.index, cursorY); cursorY += rowStep; }); } else if (positives.length) { sectionChip(cursorY, "positive"); cursorY += chipHeight + chipToRowGap; positives.forEach(row => { rowPositions.set(row.index, cursorY); cursorY += rowStep; }); } if (!usesTemporalOrder && negatives.length) { cursorY += positives.length ? groupGap : 0; sectionChip(cursorY, "negative"); cursorY += chipHeight + chipToRowGap; negatives.forEach(row => { rowPositions.set(row.index, cursorY); cursorY += rowStep; }); }
const rowLayer = svg.append("g").attr("class", "diverging-row-layer"); const labelMaxChars = 18; orderedRows.forEach(row => { const y = rowPositions.get(row.index); const centerY = y + bandHeight / 2; const rowFill = row.value >= 0 ? colors.greenSoft : colors.redSoft; rowLayer.append("rect") .attr("x", 52) .attr("y", y) .attr("width", 920) .attr("height", bandHeight) .attr("rx", 11) .attr("fill", rowFill) .attr("opacity", 0.82) .attr("data-row-category", row.category); rowLayer.append("line") .attr("x1", 52) .attr("x2", 972) .attr("y1", y + bandHeight) .attr("y2", y + bandHeight) .attr("stroke", "#e1e5e8") .attr("stroke-width", 1) .attr("stroke-dasharray", "3 4");
const slot = rowLayer.append("g") .attr("class", "reserved-asset-slot category-icon-slot") .attr("data-asset-slot", "category-icon") .attr("data-slot-policy", "input_provided_or_image2_asset") .attr("data-anchor", "row-centerline-left-label-column") .attr("data-collision-rule", "centerline-align-with-row-without-overlapping-labels-or-bars") .attr("data-category", row.category); slot.append("circle") .attr("cx", 92) .attr("cy", centerY) .attr("r", Math.min(29, bandHeight * 0.42)) .attr("fill", colors.panel) .attr("stroke", row.value >= 0 ? "#b7d9c2" : "#efb8b5") .attr("stroke-width", 2.5); slot.append("text") .attr("x", 92) .attr("y", centerY + 8) .attr("text-anchor", "middle") .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", `${Math.min(22, labelFont)}px`) .style("font-weight", 800) .style("fill", row.value >= 0 ? colors.green : colors.red) .text(row.category.slice(0, 1).toUpperCase());
const smallNegativeNearZero = row.value < 0 && Math.abs(xScale(row.value) - zeroX) < 52 && zeroX < 430; const rowLabelMaxChars = smallNegativeNearZero ? 12 : labelMaxChars; const labelLines = splitWords(row.category, rowLabelMaxChars, 2); const labelText = rowLayer.append("text") .attr("x", 142) .attr("y", centerY - ((labelLines.length - 1) * labelFont * 0.56)) .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", `${labelFont}px`) .style("font-weight", 800) .style("fill", colors.navy); labelLines.forEach((line, i) => { labelText.append("tspan") .attr("x", 142) .attr("dy", i === 0 ? 0 : labelFont * 1.12) .text(line); }); });
const plotLayer = svg.append("g").attr("class", "diverging-plot-layer"); const firstRowY = orderedRows.length ? d3.min(orderedRows, row => rowPositions.get(row.index)) : rowTop; plotLayer.append("line") .attr("x1", zeroX) .attr("x2", zeroX) .attr("y1", firstRowY + 6) .attr("y2", axisY) .attr("stroke", "#26384c") .attr("stroke-width", 2.2) .attr("opacity", 0.85) .attr("data-axis-role", "zero-line");
orderedRows.forEach(row => { const y = rowPositions.get(row.index); const centerY = y + bandHeight / 2; const barY = centerY - barHeight / 2; const endX = xScale(row.value); const barX = Math.min(zeroX, endX); const barW = Math.max(1, Math.abs(endX - zeroX)); const gradient = row.value >= 0 ? "url(#hdb02-positive-gradient)" : "url(#hdb02-negative-gradient)"; plotLayer.append("rect") .attr("x", barX) .attr("y", barY) .attr("width", barW) .attr("height", barHeight) .attr("rx", 7) .attr("fill", gradient) .attr("filter", "url(#hdb02-soft-shadow)") .attr("data-category", row.category) .attr("data-value", row.value) .attr("data-mark-role", "diverging-bar");
const text = valueFmt(row.value); let valueFontForRow = valueFont; function measureValueText(fontSize) { return chartUtils.text.measure(plotLayer, text, { fontFamily: "Arial, Helvetica, sans-serif", fontSize: `${fontSize}px`, fontWeight: 900 }).width; } let endpointTextWidth = measureValueText(valueFontForRow); const textGap = 12; let valueX = row.value >= 0 ? endX + textGap : endX - textGap; let anchor = row.value >= 0 ? "start" : "end"; let labelInsideBar = false; let compactNegativePill = null; if (row.value >= 0 && valueX > 960) { valueX = endX - textGap; anchor = "end"; labelInsideBar = true; } if (row.value < 0 && valueX < 306 && barW > endpointTextWidth + 24) { valueX = barX + textGap; anchor = "start"; labelInsideBar = true; } if (row.value < 0 && !labelInsideBar && valueX - endpointTextWidth < 330 && barW > endpointTextWidth + 24) { valueX = barX + textGap; anchor = "start"; labelInsideBar = true; } if (row.value < 0 && !labelInsideBar && valueX - endpointTextWidth < 330) { valueFontForRow = Math.max(15, valueFont * 0.78); endpointTextWidth = measureValueText(valueFontForRow); const pillPadX = 8; const pillW = endpointTextWidth + pillPadX * 2; const pillRight = zeroX - 8; const pillH = valueFontForRow * 1.18; compactNegativePill = { x: pillRight - pillW, y: centerY - pillH / 2, width: pillW, height: pillH, rx: Math.min(7, pillH / 2) }; valueX = pillRight - pillPadX; anchor = "end"; labelInsideBar = true; } if (compactNegativePill) { plotLayer.append("rect") .attr("x", compactNegativePill.x) .attr("y", compactNegativePill.y) .attr("width", compactNegativePill.width) .attr("height", compactNegativePill.height) .attr("rx", compactNegativePill.rx) .attr("fill", colors.redDark) .attr("data-label-role", "negative-value-pill"); } plotLayer.append("text") .attr("x", valueX) .attr("y", centerY + valueFontForRow * 0.36) .attr("text-anchor", anchor) .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", `${valueFontForRow}px`) .style("font-weight", 900) .style("fill", labelInsideBar ? "#ffffff" : (row.value >= 0 ? "#176ecf" : colors.redDark)) .attr("data-label-role", "value-label") .text(text); });
const tickValues = xScale.ticks(6).filter(t => t >= domainMin - 1e-9 && t <= domainMax + 1e-9); const axisLayer = svg.append("g") .attr("class", "bottom-axis") .attr("data-axis-role", "bottom-value-axis"); axisLayer.append("line") .attr("x1", x0) .attr("x2", x1) .attr("y1", axisY) .attr("y2", axisY) .attr("stroke", "#33465a") .attr("stroke-width", 1.7); tickValues.forEach(t => { const tx = xScale(t); axisLayer.append("line") .attr("x1", tx) .attr("x2", tx) .attr("y1", axisY) .attr("y2", axisY + 10) .attr("stroke", "#33465a") .attr("stroke-width", 1.4); axisLayer.append("text") .attr("x", tx) .attr("y", axisY + 34) .attr("text-anchor", "middle") .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", "18px") .style("font-weight", 500) .style("fill", colors.navy) .text(axisFmt(t)); }); axisLayer.append("text") .attr("x", (x0 + x1) / 2) .attr("y", axisY + 72) .attr("text-anchor", "middle") .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", "20px") .style("font-weight", 600) .style("letter-spacing", "1px") .style("fill", colors.muted) .text(metricLabel());
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Diverging Bar Chart", "chart_name": "horizontal_diverging_bar_chart_03", "is_composite": false, "required_fields": ["x", "y"], "required_fields_type": [["categorical"], ["numerical"]], "required_fields_range": [[2, 20], ["-inf", "inf"]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": [], "required_other_colors": ["primary","secondary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "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 jsonData = data; const chartDataRaw = (jsonData.data && jsonData.data.data) || []; const colorResolver = chartUtils.color.resolver(jsonData); const typography = jsonData.typography || {}; const variables = jsonData.variables || {}; const images = jsonData.images || { field: {}, other: {} };
const dimensionChannel = chartUtils.schema.channel(jsonData, "x"); const valueChannel = chartUtils.schema.channel(jsonData, "y"); const dimensionField = dimensionChannel.key; const valueField = valueChannel.key; const dataColumns = chartUtils.schema.columns(jsonData); const dimensionColumn = dataColumns.find(c => c.name === dimensionField) || {}; const valueUnit = valueChannel.unit || ""; const valueFieldName = valueChannel.key || valueField || "Value"; const dimensionFieldName = dimensionChannel.key || dimensionField || "Category";
d3.select(containerSelector).html("");
const width = Math.max(520, variables.width || 600); const height = Math.max(820, variables.height || Math.round(width * 1.48)); const titleText = (jsonData.titles && jsonData.titles.main_title) || (jsonData.metadata && jsonData.metadata.title) || ""; const subtitleText = (jsonData.titles && jsonData.titles.sub_title) || (jsonData.metadata && jsonData.metadata.description) || "";
const isTemporal = dimensionColumn.data_type === "temporal" || chartDataRaw.every(d => /^\d{4}$/.test(String(d[dimensionField]))); const parseTemporal = value => { const raw = String(value); if (/^\d{4}$/.test(raw)) return +raw; const parsed = Date.parse(raw); return Number.isFinite(parsed) ? parsed : raw; }; const chartData = chartDataRaw .filter(d => d && d[dimensionField] !== undefined && d[valueField] !== undefined) .map((d, index) => ({ ...d, __inputIndex: index, __value: +d[valueField] || 0 })) .sort((a, b) => { if (!isTemporal) return a.__inputIndex - b.__inputIndex; const av = parseTemporal(a[dimensionField]); const bv = parseTemporal(b[dimensionField]); if (typeof av === "number" && typeof bv === "number") return av - bv; return String(a[dimensionField]).localeCompare(String(b[dimensionField])); });
const svg = d3.select(containerSelector) .append("svg") .attr("width", "100%") .attr("height", height) .attr("viewBox", `0 0 ${width} ${height}`) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink") .attr("style", "max-width: 100%; height: auto;");
const defs = svg.append("defs"); const positiveBase = "#b01818"; const negativeBase = "#1f72d2"; const textColor = colorResolver.text({ fallback: "#343434" }).value || "#343434"; const mutedText = "#58606a"; const gridColor = "#d8d2cf";
const bgGradient = defs.append("linearGradient") .attr("id", "hdbc03-background") .attr("x1", "0%").attr("y1", "0%") .attr("x2", "100%").attr("y2", "0%"); bgGradient.append("stop").attr("offset", "0%").attr("stop-color", "#f8fcfd"); bgGradient.append("stop").attr("offset", "48%").attr("stop-color", "#fffaf8"); bgGradient.append("stop").attr("offset", "100%").attr("stop-color", "#fff7f3");
const positiveGradient = defs.append("linearGradient") .attr("id", "hdbc03-positive") .attr("x1", "0%").attr("x2", "100%") .attr("y1", "0%").attr("y2", "0%"); positiveGradient.append("stop").attr("offset", "0%").attr("stop-color", colorResolver.variant(positiveBase, { mode: "brighter", amount: 0.18 })); positiveGradient.append("stop").attr("offset", "100%").attr("stop-color", colorResolver.variant(positiveBase, { mode: "darker", amount: 0.08 }));
const negativeGradient = defs.append("linearGradient") .attr("id", "hdbc03-negative") .attr("x1", "100%").attr("x2", "0%") .attr("y1", "0%").attr("y2", "0%"); negativeGradient.append("stop").attr("offset", "0%").attr("stop-color", colorResolver.variant(negativeBase, { mode: "brighter", amount: 0.18 })); negativeGradient.append("stop").attr("offset", "100%").attr("stop-color", colorResolver.variant(negativeBase, { mode: "darker", amount: 0.08 }));
const shadow = defs.append("filter") .attr("id", "hdbc03-soft-shadow") .attr("x", "-20%").attr("y", "-20%") .attr("width", "140%").attr("height", "140%"); shadow.append("feDropShadow") .attr("dx", 0) .attr("dy", 2) .attr("stdDeviation", 3) .attr("flood-color", "#21110e") .attr("flood-opacity", 0.14);
svg.append("rect") .attr("width", width) .attr("height", height) .attr("fill", "url(#hdbc03-background)") .attr("fill-opacity", 0.62);
const titleFont = typography.title || {}; const labelFont = typography.label || {}; const annotationFont = typography.annotation || {}; const titleFamily = titleFont.font_family || "Georgia, 'Times New Roman', serif"; const sansFamily = labelFont.font_family || "Arial, Helvetica, sans-serif";
function measure(text, fontSize, fontWeight = 400, fontFamily = sansFamily) { return chartUtils.text.measure(svg, String(text), { fontFamily, fontSize: `${fontSize}px`, fontWeight }).width; }
function humanizeLabel(text) { return String(text == null ? "" : text) .replace(/_/g, " ") .replace(/([a-z0-9])([A-Z])/g, "$1 $2") .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2") .replace(/\s*-\s*/g, " - ") .replace(/\s+/g, " ") .trim(); }
function compactFieldLabel(text) { return humanizeLabel(text) .replace(/\bTemperature\b/gi, "Temp.") .replace(/\bDifferential\b/gi, "Diff.") .replace(/\bAnomaly\b/gi, "Anomaly") .replace(/\bBalance\b/gi, "Balance"); }
function addWrappedText(parent, text, x, y, maxWidth, options) { const cfg = { fontFamily: sansFamily, fontSize: 16, fontWeight: 400, fill: textColor, anchor: "middle", lineHeight: 1.18, maxLines: 2, textTransform: value => value, ...options }; const source = cfg.textTransform(String(text || "")); const words = source.split(/\s+/).filter(Boolean); const el = parent.append("text") .attr("x", x) .attr("y", y) .attr("text-anchor", cfg.anchor) .style("font-family", cfg.fontFamily) .style("font-size", `${cfg.fontSize}px`) .style("font-weight", cfg.fontWeight) .style("fill", cfg.fill); const lines = []; let line = []; words.forEach(word => { const candidate = [...line, word].join(" "); if (line.length && measure(candidate, cfg.fontSize, cfg.fontWeight, cfg.fontFamily) > maxWidth) { lines.push(line.join(" ")); line = [word]; } else { line.push(word); } }); if (line.length) lines.push(line.join(" ")); const visible = lines.slice(0, cfg.maxLines); if (lines.length > cfg.maxLines && visible.length) { let last = visible[visible.length - 1]; while (last.length > 4 && measure(`${last}...`, cfg.fontSize, cfg.fontWeight, cfg.fontFamily) > maxWidth) { last = last.split(/\s+/).slice(0, -1).join(" "); } visible[visible.length - 1] = `${last}...`; } visible.forEach((lineText, i) => { el.append("tspan") .attr("x", x) .attr("dy", i === 0 ? 0 : `${cfg.lineHeight}em`) .text(lineText); }); return el; }
function formatValue(value, opts = {}) { const abs = Math.abs(value); let text; if (abs >= 1000000) { text = `${chartUtils.format.autoText(value / 1000000)}M`; } else if (abs >= 1000) { text = `${chartUtils.format.autoText(value / 1000)}K`; } else { text = chartUtils.format.autoText(value); } const sign = value > 0 ? "+" : ""; const suffix = opts.omitUnit ? "" : valueUnit; return `${sign}${text}${suffix}`; }
function tickLabel(value, sign) { const text = formatValue(value, { omitUnit: false }).replace(/^\+/, ""); return sign < 0 ? `-${text}` : `+${text}`; }
function buildTickValues(maxValue, sideSpan) { if (maxValue <= 2 && sideSpan >= 180) { const smallStep = maxValue <= 1 ? 0.2 : 0.2; return d3.range(smallStep, maxValue + smallStep / 2, smallStep); } let target = Math.max(2, Math.min(6, Math.floor(sideSpan / 58))); let values = []; while (target >= 2) { const step = d3.tickStep(0, maxValue, target); values = d3.range(step, maxValue + step / 2, step); const minGap = values.length > 1 ? sideSpan / values.length : sideSpan; const maxLabelWidth = d3.max(values, value => Math.max( measure(tickLabel(value, -1), 10, 600), measure(tickLabel(value, 1), 10, 600) )) || 0; if (values.length <= 2 || maxLabelWidth + 12 <= minGap) break; target -= 1; } return values; }
const rows = chartData; const rowCount = Math.max(1, rows.length); const outerMargin = { left: 42, right: 42 }; const plotTop = 275; const plotBottom = height - 92; const plotHeight = Math.max(360, plotBottom - plotTop); const rowBand = plotHeight / rowCount; const rowGap = Math.max(3, Math.min(8, rowBand * 0.16)); const barHeight = Math.max(10, rowBand - rowGap);
const labelWidths = rows.map(d => measure(d[dimensionField], 21, 600)); const centerBoxMaxWidth = isTemporal ? width * 0.18 : width * 0.32; const centerBoxWidth = Math.max(64, Math.min(centerBoxMaxWidth, d3.max(labelWidths) + 24)); const centerBoxLeft = width / 2 - centerBoxWidth / 2; const centerBoxRight = centerBoxLeft + centerBoxWidth; const leftBound = outerMargin.left; const rightBound = width - outerMargin.right; const availableLeft = centerBoxLeft - leftBound; const availableRight = rightBound - centerBoxRight; const sideWidth = Math.max(40, Math.min(availableLeft, availableRight)); const chartLeft = centerBoxLeft - sideWidth; const chartRight = centerBoxRight + sideWidth;
const valueLabelSize = Math.max(12, Math.min(16, rowBand * 0.42)); const maxPositiveLabelWidth = d3.max(rows.filter(d => d.__value >= 0), d => measure(formatValue(d.__value), valueLabelSize, 700)) || 0; const maxNegativeLabelWidth = d3.max(rows.filter(d => d.__value < 0), d => measure(formatValue(d.__value), valueLabelSize, 700)) || 0; const endpointGap = 10; const maxAbsRaw = d3.max(rows, d => Math.abs(d.__value)) || 1; const reserveCapRatio = maxAbsRaw <= 2 ? 0.26 : 0.38; const positiveLabelReserve = Math.min(sideWidth * reserveCapRatio, Math.max(40, maxPositiveLabelWidth + endpointGap + 10)); const negativeLabelReserve = Math.min(sideWidth * reserveCapRatio, Math.max(40, maxNegativeLabelWidth + endpointGap + 10)); const markSideWidth = Math.max(40, sideWidth - Math.max(positiveLabelReserve, negativeLabelReserve)); const rightLabelLimit = width - 12; const leftLabelLimit = 12;
const niceMaxAbs = Math.max(1, Math.ceil(maxAbsRaw * 5) / 5); const magnitudeScale = d3.scaleLinear() .domain([0, niceMaxAbs]) .range([0, markSideWidth]); const maxAbs = magnitudeScale.domain()[1]; const tickValues = buildTickValues(maxAbs, sideWidth);
const plot = svg.append("g").attr("class", "hdbc03-plot"); const tickY = plotTop - 32; const headingY = plotTop - 78;
function addAssetChip(slotName, x, y, sideColor, symbol) { const g = svg.append("g") .attr("class", `asset-slot ${slotName}`) .attr("data-asset-slot", slotName) .attr("data-asset-source-policy", "neutral_placeholder") .attr("data-anchor", sideColor === positiveBase ? "right scale heading" : "left scale heading") .attr("data-collision-rule", "avoid heading text and tick labels"); g.append("circle") .attr("cx", x) .attr("cy", y) .attr("r", 19) .attr("fill", colorResolver.variant(sideColor, { mode: "brighter", amount: 0.78 })) .attr("stroke", colorResolver.variant(sideColor, { mode: "brighter", amount: 0.25 })) .attr("stroke-width", 1); g.append("text") .attr("x", x) .attr("y", y + 1) .attr("text-anchor", "middle") .attr("dominant-baseline", "middle") .style("font-family", sansFamily) .style("font-size", "20px") .style("font-weight", 700) .style("fill", sideColor) .text(symbol); }
addAssetChip("negative-heading-icon", chartLeft + 20, headingY + 6, negativeBase, "-"); addAssetChip("positive-heading-icon", chartRight - 20, headingY + 6, positiveBase, "+");
addWrappedText(svg, "BELOW AVERAGE", chartLeft + sideWidth * 0.58, headingY, sideWidth * 0.72, { fontFamily: sansFamily, fontSize: 14, fontWeight: 700, fill: negativeBase, anchor: "middle", maxLines: 2, lineHeight: 0.95 }); addWrappedText(svg, "ABOVE AVERAGE", centerBoxRight + sideWidth * 0.42, headingY, sideWidth * 0.72, { fontFamily: sansFamily, fontSize: 14, fontWeight: 700, fill: positiveBase, anchor: "middle", maxLines: 2, lineHeight: 0.95 }); const compactMeasure = `${compactFieldLabel(valueFieldName)}${valueUnit ? ` (${valueUnit})` : ""}`; addWrappedText(svg, compactMeasure, chartLeft + sideWidth * 0.58, headingY + 33, sideWidth * 0.72, { fontFamily: sansFamily, fontSize: 11, fontWeight: 500, fill: mutedText, anchor: "middle", maxLines: 2, lineHeight: 1.05 }); addWrappedText(svg, compactMeasure, centerBoxRight + sideWidth * 0.42, headingY + 33, sideWidth * 0.72, { fontFamily: sansFamily, fontSize: 11, fontWeight: 500, fill: mutedText, anchor: "middle", maxLines: 2, lineHeight: 1.05 });
tickValues.forEach(value => { const dx = magnitudeScale(value); const leftX = centerBoxLeft - dx; const rightX = centerBoxRight + dx; plot.append("line") .attr("x1", leftX) .attr("x2", leftX) .attr("y1", plotTop) .attr("y2", plotBottom) .attr("stroke", gridColor) .attr("stroke-width", 0.7) .attr("stroke-dasharray", "3 4"); plot.append("line") .attr("x1", rightX) .attr("x2", rightX) .attr("y1", plotTop) .attr("y2", plotBottom) .attr("stroke", gridColor) .attr("stroke-width", 0.7) .attr("stroke-dasharray", "3 4"); plot.append("text") .attr("x", leftX) .attr("y", tickY) .attr("text-anchor", "middle") .style("font-family", sansFamily) .style("font-size", "8.5px") .style("font-weight", 600) .style("fill", negativeBase) .text(tickLabel(value, -1)); plot.append("text") .attr("x", rightX) .attr("y", tickY) .attr("text-anchor", "middle") .style("font-family", sansFamily) .style("font-size", "8.5px") .style("font-weight", 600) .style("fill", positiveBase) .text(tickLabel(value, 1)); });
plot.append("line") .attr("x1", chartLeft) .attr("x2", chartRight) .attr("y1", plotTop - 8) .attr("y2", plotTop - 8) .attr("stroke", "#dfd5d1") .attr("stroke-width", 0.8);
const center = plot.append("g").attr("class", "hdbc03-center-column"); center.append("rect") .attr("x", centerBoxLeft) .attr("y", plotTop - 26) .attr("width", centerBoxWidth) .attr("height", plotHeight + 26) .attr("rx", 14) .attr("fill", "rgba(255,255,255,0.72)") .attr("stroke", "#d6d0ce") .attr("filter", "url(#hdbc03-soft-shadow)"); center.append("text") .attr("x", centerBoxLeft + centerBoxWidth / 2) .attr("y", plotTop - 8) .attr("text-anchor", "middle") .style("font-family", sansFamily) .style("font-size", "16px") .style("font-weight", 700) .style("fill", "#4a4a4a") .text(humanizeLabel(dimensionFieldName || "YEAR").toUpperCase());
rows.forEach((d, index) => { const y0 = plotTop + index * rowBand; center.append("line") .attr("x1", centerBoxLeft) .attr("x2", centerBoxRight) .attr("y1", y0) .attr("y2", y0) .attr("stroke", "#dcd6d3") .attr("stroke-width", 0.75); }); center.append("line") .attr("x1", centerBoxLeft) .attr("x2", centerBoxRight) .attr("y1", plotBottom) .attr("y2", plotBottom) .attr("stroke", "#dcd6d3") .attr("stroke-width", 0.75);
const barLayer = plot.append("g").attr("class", "hdbc03-bars"); const labelLayer = plot.append("g").attr("class", "hdbc03-labels"); const occupiedBoxes = [];
function addRowLabel(parent, text, x, cy, maxWidth, fontSize) { const words = String(text).split(/\s+/).filter(Boolean); const lines = []; let line = ""; words.forEach(token => { const candidate = line ? `${line} ${token}` : token; if (line && measure(candidate, fontSize, 600, sansFamily) > maxWidth) { lines.push(line.trim()); line = token.trim(); } else { line = candidate; } }); if (line) lines.push(line.trim()); const visible = lines.slice(0, 2); if (lines.length > 2 && visible.length) { let last = visible[visible.length - 1]; while (last.length > 3 && measure(`${last}...`, fontSize, 600, sansFamily) > maxWidth) { last = last.slice(0, -1); } visible[visible.length - 1] = `${last}...`; } const textEl = parent.append("text") .attr("x", x) .attr("y", cy - ((visible.length - 1) * fontSize * 0.56)) .attr("text-anchor", "middle") .style("font-family", sansFamily) .style("font-size", `${fontSize}px`) .style("font-weight", 600) .style("fill", "#3f4146"); visible.forEach((lineText, i) => { textEl.append("tspan") .attr("x", x) .attr("dy", i === 0 ? "0.35em" : "1.05em") .text(lineText); }); }
rows.forEach((d, index) => { const rawValue = d.__value; const isPositive = rawValue >= 0; const y = plotTop + index * rowBand + rowGap / 2; const cy = y + barHeight / 2; const barWidth = Math.max(2, magnitudeScale(Math.abs(rawValue))); const x = isPositive ? centerBoxRight : centerBoxLeft - barWidth; const fill = isPositive ? "url(#hdbc03-positive)" : "url(#hdbc03-negative)"; const radius = Math.min(barHeight / 2, 14);
const path = isPositive ? `M ${centerBoxRight},${y} L ${x + barWidth - radius},${y} a ${radius},${radius} 0 0 1 0,${barHeight} L ${centerBoxRight},${y + barHeight} Z` : `M ${centerBoxLeft},${y} L ${x + radius},${y} a ${radius},${radius} 0 0 0 0,${barHeight} L ${centerBoxLeft},${y + barHeight} Z`;
barLayer.append("path") .attr("d", path) .attr("fill", fill) .attr("data-category", d[dimensionField]) .attr("data-value", rawValue) .attr("data-sample-index", d.__inputIndex) .attr("stroke", variables.has_stroke ? "rgba(255,255,255,0.7)" : "none") .attr("stroke-width", variables.has_stroke ? 0.8 : 0);
addRowLabel( center, humanizeLabel(d[dimensionField]), centerBoxLeft + centerBoxWidth / 2, cy, centerBoxWidth - 12, Math.max(10, Math.min(isTemporal ? 21 : 13, rowBand * (isTemporal ? 0.46 : 0.34))) );
const valueText = formatValue(rawValue); const labelSize = valueLabelSize; const labelWidth = measure(valueText, labelSize, 700); const gap = endpointGap; const centerClearance = Math.max(12, Math.min(18, barHeight * 0.22)); const endpointX = isPositive ? centerBoxRight + barWidth : centerBoxLeft - barWidth; const shortBar = barWidth < labelWidth + gap * 2 + centerClearance; let labelX; let anchor; let labelInside = false; let labelHalo = false; if (isPositive) { const outsideStart = Math.max(endpointX + gap, centerBoxRight + centerClearance); const safeOutsideStart = Math.min(outsideStart, Math.max(centerBoxRight + centerClearance, rightLabelLimit - labelWidth)); const outsideFits = safeOutsideStart + labelWidth <= rightLabelLimit && safeOutsideStart >= endpointX + Math.max(2, gap * 0.45); if (outsideFits || shortBar) { labelX = outsideFits ? safeOutsideStart : Math.max(centerBoxRight + centerClearance, rightLabelLimit - labelWidth); anchor = "start"; labelInside = false; labelHalo = true; } else { labelX = Math.min(chartRight - 2, endpointX - gap); anchor = "end"; labelInside = true; } } else { const outsideEnd = Math.min(endpointX - gap, centerBoxLeft - centerClearance); const safeOutsideEnd = Math.max(outsideEnd, Math.min(centerBoxLeft - centerClearance, leftLabelLimit + labelWidth)); const outsideFits = safeOutsideEnd - labelWidth >= leftLabelLimit && safeOutsideEnd <= endpointX - Math.max(2, gap * 0.45); if (outsideFits || shortBar) { labelX = outsideFits ? safeOutsideEnd : Math.min(centerBoxLeft - centerClearance, leftLabelLimit + labelWidth); anchor = "end"; labelInside = false; labelHalo = true; } else { labelX = Math.max(chartLeft + 2, endpointX + gap); anchor = "start"; labelInside = true; } } labelLayer.append("text") .attr("x", labelX) .attr("y", cy) .attr("dy", "0.35em") .attr("text-anchor", anchor) .style("font-family", annotationFont.font_family || sansFamily) .style("font-size", `${labelSize}px`) .style("font-weight", 700) .style("paint-order", labelHalo ? "stroke" : null) .style("stroke", labelHalo ? "#fffaf7" : null) .style("stroke-width", labelHalo ? "3px" : null) .style("stroke-linejoin", labelHalo ? "round" : null) .style("fill", labelInside ? "#fff7f2" : (isPositive ? positiveBase : negativeBase)) .text(valueText);
occupiedBoxes.push({ x: Math.min(x, labelX - labelWidth), y, w: Math.max(barWidth, Math.abs(labelX - x) + labelWidth), h: barHeight }); });
function boxesOverlap(a, b, pad = 0) { return !(a.x + a.w + pad < b.x || b.x + b.w + pad < a.x || a.y + a.h + pad < b.y || b.y + b.h + pad < a.y); }
const imageHref = images.other && images.other.primary; const rawImagePolicy = images.other && ( images.other.primary_source_policy || images.other.primarySourcePolicy || images.other.source_policy || images.other.sourcePolicy || images.other.asset_source_policy || images.other.assetSourcePolicy ); const normalizedImagePolicy = String(rawImagePolicy || "").toLowerCase().replace(/-/g, "_"); const classifiedImagePolicy = normalizedImagePolicy.includes("input") ? "input_asset" : (normalizedImagePolicy.includes("retrieval") ? "retrieval_asset" : (normalizedImagePolicy.includes("image2") ? "image2_asset" : "")); const canRenderClassifiedImage = Boolean(imageHref && classifiedImagePolicy); const slotW = Math.min(sideWidth * 0.96, width * 0.39); let slotH = Math.min(slotW * 1.10, height * 0.34); let slotX = chartLeft + sideWidth * 0.02; let slotY = plotTop + plotHeight * 0.43; slotH = Math.min(slotH, Math.max(124, plotBottom - slotY - 10)); const proposedSlot = { x: slotX, y: slotY, w: slotW, h: slotH }; let collides = occupiedBoxes.some(box => boxesOverlap(proposedSlot, box, 8)); if (collides) { slotY = plotTop + plotHeight * 0.50; proposedSlot.y = slotY; collides = occupiedBoxes.some(box => boxesOverlap(proposedSlot, box, 8)); } function addNeutralContextSlot(visible) { const slot = svg.append("g") .attr("class", "asset-slot context-image-slot") .attr("data-asset-slot", "context-image") .attr("data-asset-source-policy", "neutral_placeholder") .attr("data-slot-policy", "neutral_placeholder_or_image2_asset") .attr("data-reserved-slot", "context_image_slot") .attr("data-anchor", "negative-side lower plot area") .attr("data-collision-rule", "avoid bars, value labels, center column, heading/tick rows, and chart edges") .attr("data-bbox", `${slotX.toFixed(2)},${slotY.toFixed(2)},${slotW.toFixed(2)},${slotH.toFixed(2)}`) .attr("data-mask-policy", "downstream image2 may replace only within this rounded bbox") .attr("data-collision-result", visible ? "visible_clear" : "hidden_due_to_collision_or_insufficient_space"); if (visible) { slot.attr("opacity", 0.76); } if (!visible) { slot.append("rect") .attr("x", slotX) .attr("y", slotY) .attr("width", slotW) .attr("height", slotH) .attr("rx", 18) .attr("fill", "none") .attr("stroke", "none"); return; } const strokeWidth = Math.max(1.4, Math.min(2.4, slotW * 0.014)); slot.append("rect") .attr("x", slotX) .attr("y", slotY) .attr("width", slotW) .attr("height", slotH) .attr("rx", 18) .attr("fill", "#ffffff") .attr("fill-opacity", 0.20) .attr("stroke", "#91A5B0") .attr("stroke-width", strokeWidth) .attr("stroke-dasharray", `${Math.max(7, slotW * 0.05)} ${Math.max(6, slotW * 0.04)}`); slot.append("rect") .attr("x", slotX + slotW * 0.18) .attr("y", slotY + slotH * 0.18) .attr("width", slotW * 0.64) .attr("height", slotH * 0.64) .attr("rx", 14) .attr("fill", "none") .attr("stroke", "#91A5B0") .attr("stroke-width", Math.max(1.1, strokeWidth * 0.75)) .attr("opacity", 0.42); slot.append("path") .attr("d", `M ${slotX + slotW * 0.26},${slotY + slotH * 0.68} L ${slotX + slotW * 0.42},${slotY + slotH * 0.50} L ${slotX + slotW * 0.56},${slotY + slotH * 0.61} L ${slotX + slotW * 0.74},${slotY + slotH * 0.38}`) .attr("fill", "none") .attr("stroke", "#91A5B0") .attr("stroke-width", Math.max(1.2, strokeWidth * 0.9)) .attr("stroke-linecap", "round") .attr("stroke-linejoin", "round") .attr("opacity", 0.44); slot.append("circle") .attr("cx", slotX + slotW * 0.35) .attr("cy", slotY + slotH * 0.34) .attr("r", Math.min(slotW, slotH) * 0.055) .attr("fill", "#91A5B0") .attr("opacity", 0.42); }
if (canRenderClassifiedImage && !collides && slotY + slotH < plotBottom - 4) { const clipId = "hdbc03-context-image-clip"; defs.append("clipPath").attr("id", clipId) .append("rect") .attr("x", slotX) .attr("y", slotY) .attr("width", slotW) .attr("height", slotH) .attr("rx", 18); const slot = svg.append("g") .attr("class", "asset-slot context-image-slot") .attr("data-asset-slot", "context-image") .attr("data-asset-source-policy", classifiedImagePolicy) .attr("data-slot-policy", `${classifiedImagePolicy}_or_image2_asset`) .attr("data-reserved-slot", "context_image_slot") .attr("data-anchor", "negative-side lower plot area") .attr("data-collision-rule", "avoid bars, value labels, center column, heading/tick rows, and chart edges") .attr("data-bbox", `${slotX.toFixed(2)},${slotY.toFixed(2)},${slotW.toFixed(2)},${slotH.toFixed(2)}`) .attr("data-mask-policy", "visible image clipped to this rounded bbox; downstream image2 may replace only within bbox") .attr("data-collision-result", "visible_clear"); slot.append("image") .attr("x", slotX) .attr("y", slotY) .attr("width", slotW) .attr("height", slotH) .attr("preserveAspectRatio", "xMidYMid slice") .attr("href", imageHref) .attr("clip-path", `url(#${clipId})`) .attr("opacity", 0.78); } else { addNeutralContextSlot(!collides && slotY + slotH < plotBottom - 4); }
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576/*REQUIREMENTS_BEGIN{ "chart_type": "Diverging Bar Chart", "chart_name": "diverging_bar_plain_chart_03", "chart_for": "comparison", "is_composite": false, "required_fields": ["x", "y", "group"], "required_fields_type": [["categorical"], ["numerical"], ["categorical"]], "required_fields_range": [[2, 20], [0, "inf"], [2, 2]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["group"], "required_other_colors": [], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "styled", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 水平对比型条形图实现 - 使用D3.js horizontal_split_bar_chart_01function makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; // 完整的JSON数据对象 const chartData = jsonData.data.data // 实际数据点数组 const variables = jsonData.variables || {}; // 图表配置,如果不存在则使用空对象 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" } }; const colors = jsonData.colors || { text_color: "#333333" }; // 颜色设置,如果不存在则使用默认值 const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; // 图像(国旗等) const dataColumns = chartUtils.schema.columns(jsonData); // 数据列定义 // 检查并设置缺失的视觉效果变量,确保不会因为缺少变量而出错 variables.has_rounded_corners = variables.has_rounded_corners || false; variables.has_shadow = variables.has_shadow || false; variables.has_gradient = variables.has_gradient || false; variables.has_stroke = variables.has_stroke || false; variables.has_spacing = variables.has_spacing || false; // 数值格式化函数 // 清空容器 - 在添加新图表前移除可能存在的内容 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表总尺寸和边距 const width = variables.width; // 图表总宽度 const height = variables.height; // 图表总高度 // 边距:top-顶部,right-右侧,bottom-底部,left-左侧 const margin = { top: 100, right: 70, bottom: 40, left: 70 }; // 计算实际绘图区域尺寸 const innerWidth = width - margin.left - margin.right; // 绘图区宽度 const innerHeight = height - margin.top - margin.bottom; // 绘图区高度 // 设置各部分位置参数 const centerX = margin.left + innerWidth / 2; // 图表中心X坐标 const topAreaHeight = 60; // 标题和标签区域高度 const barPadding = 8; // 条形图之间的间距 // ---------- 3. 提取字段名和单位 ---------- // 根据数据列顺序提取字段名 const dimensionField = chartUtils.schema.channel(jsonData, "x").key; const valueField = chartUtils.schema.channel(jsonData, "y").key; const groupField = chartUtils.schema.channel(jsonData, "group").key; // 获取字段单位(如果存在) let dimensionUnit = ""; let valueUnit = ""; // 默认为百分比 let groupUnit = ""; if (chartUtils.schema.channel(jsonData, "x").unit !== "none") { dimensionUnit = chartUtils.schema.channel(jsonData, "x").unit; } if (chartUtils.schema.channel(jsonData, "y").unit !== "none") { valueUnit = chartUtils.schema.channel(jsonData, "y").unit; } if (chartUtils.schema.channel(jsonData, "group").unit!== "none") { groupUnit = chartUtils.schema.channel(jsonData, "group").unit; } // ---------- 4. 数据处理 ---------- // 获取唯一维度值和分组值 const allDimensions = [...new Set(chartData.map(d => d[dimensionField]))]; const groups = [...new Set(chartData.map(d => d[groupField]))]; // 不对维度进行排序,直接使用原始顺序 const dimensions = [...allDimensions]; // 使用前两个分组作为左右两侧显示数据 const leftGroup = groups[0]; // 左侧分组 const rightGroup = groups[1]; // 右侧分组 // 如果存在第三个分组,可以用作总计分组(用于���示右侧的总数值) const totalGroup = groups.length > 2 ? groups[2] : null; // ---------- 5. 动态计算维度标签区域宽度 ---------- // Check if we should show icons along with text const showIcons = jsonData.variation?.axis_label === "side"; // 标志尺寸 const flagWidth = 20; const flagHeight = 15; const flagPadding = 0; // 计算最大标签宽度 let maxLabelWidth = 0; dimensions.forEach(dimension => { // 格式化维度名称(附加单位,如果有) const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; const textWidth = chartUtils.text.measure(null, formattedDimension, { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }).width; const totalWidth = showIcons ? flagWidth + flagPadding + textWidth : textWidth + 5; maxLabelWidth = Math.max(maxLabelWidth, totalWidth); }); // 为计算出的宽度添加边距,确保有足够空间 const dimensionLabelWidth = Math.max(maxLabelWidth + 5, 80); // 最小值为80像素 // ---------- 6. 创建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"); // ---------- 6.1 创建视觉效果 ---------- const defs = svg.append("defs"); const getColor = (group) => { return colorResolver.field(group, 0, { fallbackKey: "primary" }).value; }; if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 4); filter.append("feOffset") .attr("dx", 4) .attr("dy", 4) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } if (variables.has_gradient) { const leftGradientId = `gradient-${leftGroup.replace(/\s+/g, '-').toLowerCase()}`; const leftBaseColor = getColor(leftGroup); const leftGradient = defs.append("linearGradient") .attr("id", leftGradientId) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); leftGradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(leftBaseColor, { mode: "brighter", amount: 1.2 })); leftGradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(leftBaseColor, { mode: "darker", amount: 0.7 })); const rightGradientId = `gradient-${rightGroup.replace(/\s+/g, '-').toLowerCase()}`; const rightBaseColor = getColor(rightGroup); const rightGradient = defs.append("linearGradient") .attr("id", rightGradientId) .attr("x1", "100%") .attr("y1", "0%") .attr("x2", "0%") .attr("y2", "0%"); rightGradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(rightBaseColor, { mode: "brighter", amount: 1.2 })); rightGradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(rightBaseColor, { mode: "darker", amount: 0.7 })); }
// ---------- 7. 添加左右组标签 ---------- const formattedLeftGroup = groupUnit ? `${leftGroup}${groupUnit}` : `${leftGroup}`; svg.append("text") .attr("x", margin.left + innerWidth / 4) .attr("y", margin.top - 10) .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedLeftGroup); const formattedRightGroup = groupUnit ? `${rightGroup}${groupUnit}` : `${rightGroup}`; svg.append("text") .attr("x", margin.left + innerWidth * 3 / 4) .attr("y", margin.top - 10) .attr("text-anchor", "middle") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) .text(formattedRightGroup); // ---------- 8. 创建绘图组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left},${margin.top})`); // ---------- 9. 创建比例尺 ---------- const yScale = d3.scaleBand() .domain(dimensions) .range([0, innerHeight]) .padding(variables.has_spacing ? 0.4 : 0.3); const maxLeftValue = d3.max(chartData.filter(d => d[groupField] === leftGroup), d => +d[valueField]); const maxRightValue = d3.max(chartData.filter(d => d[groupField] === rightGroup), d => +d[valueField]); const leftXScale = d3.scaleLinear() .domain([0, maxLeftValue]) .range([innerWidth / 2 - dimensionLabelWidth/2, 0]); const rightXScale = d3.scaleLinear() .domain([0, maxRightValue]) .range([0, innerWidth / 2 - dimensionLabelWidth/2]); const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.available(0, { fallback: "#333333" }).value; }; const strokeColor = getStrokeColor(); // ---------- 9. 添加交替行背景 ---------- if (jsonData.variation?.background === "styled") { dimensions.forEach((dimension, i) => { if (i % 2 === 0) { g.append("rect") .attr("x", -margin.left/2) .attr("y", yScale(dimension)) .attr("width", innerWidth + margin.left/2 + margin.right/2) .attr("height", yScale.bandwidth()) .attr("class","background") .attr("fill", "#f5f5f5") .attr("opacity", 0.8); } }); } // ---------- 10. 绘制维度标签和图标 ---------- dimensions.forEach(dimension => { const yPos = yScale(dimension) + yScale.bandwidth() / 2; const flagWidth = 20; const flagHeight = 15; const flagPadding = 0; const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`; const textWidth = chartUtils.text.measure(g, formattedDimension, { fontFamily: typography.label.font_family, fontSize: typography.label.font_size, fontWeight: typography.label.font_weight }).width; if (showIcons) { // If showing icons, calculate total width including the icon const totalWidth = flagWidth + flagPadding + textWidth; const startX = innerWidth/2 - totalWidth/2; // Add icon if it exists and if we should show icons if (images.field && images.field[dimension]) { g.append("image") .attr("x", startX) .attr("y", yPos - flagHeight/2) .attr("width", flagWidth) .attr("height", flagHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // Add text after the icon g.append("text") .attr("x", startX + flagWidth + flagPadding) .attr("y", yPos) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight", typography.label.font_weight) .text(formattedDimension); } else { // If not showing icons, center the text only const startX = innerWidth/2; // Add centered text without icon g.append("text") .attr("x", startX) .attr("y", yPos) .attr("dy", "0.35em") .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) .style("font-weight", typography.label.font_weight) .text(formattedDimension); } }); // ---------- 11. 绘制左侧条形图 ---------- dimensions.forEach(dimension => { const dataPoint = chartData.find(d => d[dimensionField] === dimension && d[groupField] === leftGroup ); if (dataPoint) { const barWidth = innerWidth/2 - dimensionLabelWidth/2 - leftXScale(+dataPoint[valueField]); const yPos = yScale(dimension); // ★ 改动处:让"右边缘"竖直,"左边缘"倾斜,下边比上边略宽 const slopeLeft = 5; // 下边较上边多出的宽度 const xStart = leftXScale(+dataPoint[valueField]); const barHeight = yScale.bandwidth(); // 顶部:从 xStart 到 xStart + barWidth(右侧垂直线起点) // 底部:右侧同样 xStart + barWidth,左侧 xStart - slopeLeft const pathDataLeft = [ `M ${xStart} ${yPos}`, // 左上 `L ${xStart + barWidth} ${yPos}`, // 右上(竖直边的上端) `L ${xStart + barWidth} ${yPos + barHeight}`, // 右下(竖直边的下端) `L ${xStart - slopeLeft} ${yPos + barHeight}`, // 左下(向左偏移 slope) "Z" ].join(" "); g.append("path") .attr("d", pathDataLeft) .attr("fill", variables.has_gradient ? `url(#gradient-${leftGroup.replace(/\s+/g, '-').toLowerCase()})` : getColor(leftGroup) ) .attr("rx", variables.has_rounded_corners ? 4 : 0) .attr("ry", variables.has_rounded_corners ? 4 : 0) .style("stroke", variables.has_stroke ? strokeColor : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function(event, d) { d3.select(this) .transition() .duration(100) .attr("opacity", 0.8); }) .on("mouseout", function(event, d) { d3.select(this) .transition() .duration(100) .attr("opacity", 1); }); // ------- 以下是数值标签原逻辑,不作改动 ------- const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; const valueLabelFontSize = `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`; const textWidth = chartUtils.text.measure(g, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: valueLabelFontSize, fontWeight: typography.annotation.font_weight }).width; let textX = leftXScale(+dataPoint[valueField]) + barWidth/2; const rightBoundary = leftXScale(+dataPoint[valueField]) + barWidth; if (textX + textWidth/2 > rightBoundary) { textX = rightBoundary - textWidth/2 - 2; } g.append("text") .attr("class", "label") .attr("x", leftXScale(+dataPoint[valueField]) - slopeLeft*1.5) // More generous padding .attr("y", yPos + yScale.bandwidth()/2) .attr("dy", "0.35em") .attr("text-anchor", "end") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("pointer-events", "none") .text(formattedValue);
// if (barWidth < textWidth) { // g.append("text") // .attr("class", "label") // .attr("x", leftXScale(+dataPoint[valueField]) - slopeLeft) // More generous padding // .attr("y", yPos + yScale.bandwidth()/2) // .attr("dy", "0.35em") // .attr("text-anchor", "end") // .style("fill", colorResolver.text({ fallback: "#333333" }).value) // .style("font-family", typography.annotation.font_family) // .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) // .style("font-weight", typography.annotation.font_weight) // .style("pointer-events", "none") // .text(formattedValue); // } else { // g.append("text") // .attr("class", "label") // .attr("x", textX) // .attr("y", yPos + yScale.bandwidth()/2) // .attr("dy", "0.35em") // .attr("text-anchor", "middle") // .style("fill", "#ffffff") // .style("font-family", typography.annotation.font_family) // .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) // .style("font-weight", typography.annotation.font_weight) // .style("pointer-events", "none") // .text(formattedValue); // } } }); // ---------- 12. 绘制右侧条形图 ---------- dimensions.forEach(dimension => { const dataPoint = chartData.find(d => d[dimensionField] === dimension && d[groupField] === rightGroup ); if (dataPoint) { const barWidth = rightXScale(+dataPoint[valueField]); const yPos = yScale(dimension); const barLeft = innerWidth/2 + dimensionLabelWidth/2; // ★ 改动处:让"左边缘"竖直,"右边缘"倾斜,下边比上边略宽 const slopeRight = 5; // 下边比上边多出的宽度 const barHeight = yScale.bandwidth(); // 顶部:从 barLeft 到 barLeft + barWidth(左侧竖直线为barLeft) // 底部:左侧同样 barLeft,右侧为 barLeft + barWidth + slopeRight const pathDataRight = [ `M ${barLeft} ${yPos}`, // 左上(竖直边的上端) `L ${barLeft + barWidth} ${yPos}`, // 右上 `L ${barLeft + barWidth + slopeRight} ${yPos + barHeight}`, // 右下(向右偏移 slope) `L ${barLeft} ${yPos + barHeight}`, // 左下(竖直边的下端) "Z" ].join(" "); g.append("path") .attr("d", pathDataRight) .attr("fill", variables.has_gradient ? `url(#gradient-${rightGroup.replace(/\s+/g, '-').toLowerCase()})` : getColor(rightGroup) ) .attr("rx", variables.has_rounded_corners ? 4 : 0) .attr("ry", variables.has_rounded_corners ? 4 : 0) .style("stroke", variables.has_stroke ? strokeColor : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function(event, d) { d3.select(this) .transition() .duration(100) .attr("opacity", 0.8); }) .on("mouseout", function(event, d) { d3.select(this) .transition() .duration(100) .attr("opacity", 1); }); // ------- 以下是数值标签原逻辑,不作改动 ------- const formattedValue = valueUnit ? `${chartUtils.format.autoText(+dataPoint[valueField])}${valueUnit}` : `${chartUtils.format.autoText(+dataPoint[valueField])}`; const valueLabelFontSize = `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`; const textWidth = chartUtils.text.measure(g, formattedValue, { fontFamily: typography.annotation.font_family, fontSize: valueLabelFontSize, fontWeight: typography.annotation.font_weight }).width; let textX = barLeft + barWidth/2; if (textX - textWidth/2 < barLeft) { textX = barLeft + textWidth/2 + 2; } g.append("text") .attr("class", "label") .attr("x", barLeft + barWidth + slopeRight*2) .attr("y", yPos + yScale.bandwidth()/2) .attr("dy", "0.35em") .attr("text-anchor", "start") .style("fill", colorResolver.text({ fallback: "#333333" }).value) .style("font-family", typography.annotation.font_family) .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) .style("font-weight", typography.annotation.font_weight) .style("pointer-events", "none") .text(formattedValue); // if (barWidth < textWidth) { // g.append("text") // .attr("class", "label") // .attr("x", barLeft + barWidth + slopeRight*1.4) // .attr("y", yPos + yScale.bandwidth()/2) // .attr("dy", "0.35em") // .attr("text-anchor", "start") // .style("fill", colorResolver.text({ fallback: "#333333" }).value) // .style("font-family", typography.annotation.font_family) // .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) // .style("font-weight", typography.annotation.font_weight) // .style("pointer-events", "none") // .text(formattedValue); // } else { // g.append("text") // .attr("class", "label") // .attr("x", textX) // .attr("y", yPos + yScale.bandwidth()/2) // .attr("dy", "0.35em") // .attr("text-anchor", "middle") // .style("fill", "#ffffff") // .style("font-family", typography.annotation.font_family) // .style("font-size", `${Math.min(20,Math.max(barHeight * 0.6, parseFloat(typography.annotation.font_size)))}px`) // .style("font-weight", typography.annotation.font_weight) // .style("pointer-events", "none") // .text(formattedValue); // } } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Diverging Bar Chart", "chart_name": "horizontal_diverging_bar_chart_04_hand", "chart_for": "comparison", "is_composite": false, "required_fields": ["x", "y", "group"], "required_fields_type": [["categorical"], ["numerical"], ["categorical"]], "required_fields_range": [[2, 20], [0, "inf"], [2, 2]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["group"], "required_other_colors": [], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "styled", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const jsonData = data; const rowsRaw = (jsonData.data && jsonData.data.data) || []; const typography = jsonData.typography || {}; const images = jsonData.images || { field: {}, other: {} }; const fieldImages = images.field || {}; const primaryImage = images.other && images.other.primary; const colorResolver = chartUtils.color.resolver(jsonData); const columns = chartUtils.schema.columns(jsonData); const dimensionChannel = chartUtils.schema.channel(jsonData, "x"); const valueChannel = chartUtils.schema.channel(jsonData, "y"); const groupChannel = chartUtils.schema.channel(jsonData, "group"); const dimensionField = dimensionChannel.key; const valueField = valueChannel.key; const groupField = groupChannel.key; const valueUnit = valueChannel.unit && valueChannel.unit !== "none" ? valueChannel.unit : ""; const dimensionColumn = columns.find(c => c.name === dimensionField) || {};
d3.select(containerSelector).html("");
const width = 1024; const height = 1536; const titleText = (jsonData.titles && jsonData.titles.main_title) || (jsonData.metadata && jsonData.metadata.title) || "Diverging Comparison"; const subtitleText = (jsonData.titles && jsonData.titles.sub_title) || (jsonData.metadata && jsonData.metadata.description) || jsonData.description || "";
function safeId(value) { return String(value || "") .replace(/[^a-zA-Z0-9_-]+/g, "-") .replace(/^-+|-+$/g, "") .toLowerCase() || "item"; }
function humanize(value) { return String(value == null ? "" : value) .replace(/_/g, " ") .replace(/\s+/g, " ") .trim(); }
const isTemporal = dimensionColumn.data_type === "temporal" || rowsRaw.every(d => /^\d{4}$/.test(String(d[dimensionField]))); function parseTemporal(value) { const raw = String(value); if (/^\d{4}$/.test(raw)) return +raw; const parsed = Date.parse(raw); return Number.isFinite(parsed) ? parsed : raw; }
const groups = [...new Set(rowsRaw.map(d => d[groupField]).filter(v => v !== undefined))].slice(0, 2); const leftGroup = groups[0] || "Left"; const rightGroup = groups[1] || "Right"; let dimensions = [...new Set(rowsRaw.map(d => d[dimensionField]).filter(v => v !== undefined))]; if (isTemporal) { dimensions = dimensions.sort((a, b) => { const av = parseTemporal(a); const bv = parseTemporal(b); if (typeof av === "number" && typeof bv === "number") return av - bv; return String(a).localeCompare(String(b)); }); }
const lookup = new Map(); rowsRaw.forEach((d, i) => { lookup.set(`${d[dimensionField]}|||${d[groupField]}`, { ...d, __inputIndex: i, __value: +d[valueField] || 0 }); }); const rowData = dimensions.map((dimension, index) => ({ dimension, index, left: lookup.get(`${dimension}|||${leftGroup}`), right: lookup.get(`${dimension}|||${rightGroup}`) })).filter(row => row.left || row.right); const rowCount = Math.max(1, rowData.length);
function groupColor(group, fallback, side) { const resolved = colorResolver.field(group, 0, { fallbackKey: side === "left" ? "primary" : "secondary" }).value; return resolved || fallback; } const leftColor = groupColor(leftGroup, "#2565D9", "left"); const rightColor = groupColor(rightGroup, "#FF6B1A", "right"); const titleColor = "#070B28"; const mutedText = "#3E4652";
const svg = d3.select(containerSelector) .append("svg") .attr("width", width) .attr("height", height) .attr("viewBox", `0 0 ${width} ${height}`) .attr("preserveAspectRatio", "xMidYMid meet") .attr("xmlns", "http://www.w3.org/2000/svg") .attr("xmlns:xlink", "http://www.w3.org/1999/xlink") .attr("style", "max-width: 100%; height: auto;");
const defs = svg.append("defs"); const bg = defs.append("linearGradient") .attr("id", "hdbc04hand-bg") .attr("x1", "0%").attr("y1", "0%") .attr("x2", "100%").attr("y2", "100%"); bg.append("stop").attr("offset", "0%").attr("stop-color", "#F7F6FF"); bg.append("stop").attr("offset", "55%").attr("stop-color", "#F2F5FF"); bg.append("stop").attr("offset", "100%").attr("stop-color", "#EFF5FF");
function addGradient(id, base, side) { const gradient = defs.append("linearGradient") .attr("id", id) .attr("x1", side === "left" ? "100%" : "0%") .attr("x2", side === "left" ? "0%" : "100%") .attr("y1", "0%") .attr("y2", "0%"); gradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(base, { mode: "darker", amount: 0.08 })); gradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(base, { mode: "brighter", amount: 0.18 })); } addGradient("hdbc04hand-left-bar", leftColor, "left"); addGradient("hdbc04hand-right-bar", rightColor, "right");
const shadow = defs.append("filter") .attr("id", "hdbc04hand-soft-shadow") .attr("x", "-20%").attr("y", "-20%") .attr("width", "140%").attr("height", "140%"); shadow.append("feDropShadow") .attr("dx", 0) .attr("dy", 8) .attr("stdDeviation", 9) .attr("flood-color", "#51607A") .attr("flood-opacity", 0.16);
svg.append("rect") .attr("x", 0).attr("y", 0) .attr("width", width).attr("height", height) .attr("fill", "url(#hdbc04hand-bg)");
function measure(text, fontSize, fontWeight = 400, family = "Arial, Helvetica, sans-serif") { return chartUtils.text.measure(svg, String(text || ""), { fontFamily: family, fontSize: `${fontSize}px`, fontWeight }).width; }
function wrapLines(text, maxWidth, fontSize, fontWeight, maxLines, family = "Arial, Helvetica, sans-serif") { const words = String(text || "").split(/\s+/).filter(Boolean); const lines = []; let current = ""; words.forEach(word => { const candidate = current ? `${current} ${word}` : word; if (current && measure(candidate, fontSize, fontWeight, family) > maxWidth) { lines.push(current); current = word; } else { current = candidate; } }); if (current) lines.push(current); const visible = lines.slice(0, maxLines); if (lines.length > maxLines && visible.length) { let last = visible[visible.length - 1]; while (last.length > 4 && measure(`${last}...`, fontSize, fontWeight, family) > maxWidth) { const next = last.split(/\s+/).slice(0, -1).join(" "); if (!next) break; last = next; } visible[visible.length - 1] = `${last}...`; } return visible.length ? visible : [""]; }
function addWrappedText(parent, text, x, y, maxWidth, options) { const cfg = { fontFamily: "Arial, Helvetica, sans-serif", fontSize: 24, fontWeight: 400, fill: mutedText, anchor: "start", lineHeight: 1.22, maxLines: 3, ...options }; const lines = wrapLines(text, maxWidth, cfg.fontSize, cfg.fontWeight, cfg.maxLines, cfg.fontFamily); const el = parent.append("text") .attr("x", x) .attr("y", y) .attr("text-anchor", cfg.anchor) .style("font-family", cfg.fontFamily) .style("font-size", `${cfg.fontSize}px`) .style("font-weight", cfg.fontWeight) .style("fill", cfg.fill) .style("letter-spacing", "0"); lines.forEach((line, i) => { el.append("tspan") .attr("x", x) .attr("dy", i === 0 ? 0 : `${cfg.lineHeight}em`) .text(line); }); return { element: el, lines }; }
function formatValue(value) { const abs = Math.abs(value); let text; if (abs >= 1000) { const scaled = value / 1000; text = `${Number.isInteger(scaled) ? scaled.toFixed(0) : scaled.toFixed(1).replace(/0$/, "").replace(/\.$/, "")}K`; } else if (abs >= 10) { text = Number.isInteger(value) ? String(value) : value.toFixed(1).replace(/0$/, "").replace(/\.$/, ""); } else { text = chartUtils.format.autoText(value); } return `${text}${valueUnit && !text.endsWith(valueUnit) ? valueUnit : ""}`; }
const hasHeaderAssetCandidate = !!primaryImage; function hasCategoryAssetCandidate(dimension) { return !!fieldImages[dimension]; }
const headerArt = { x: 58, y: 64, w: 310, h: 370 }; const titleBox = { x: 384, y: 116, w: 600, h: 230 }; const artSlot = svg.append("g") .attr("class", "asset-slot header-thematic-art-slot") .attr("data-asset-slot", "header-thematic-art") .attr("data-reserved-slot", "header_thematic_art") .attr("data-asset-source-policy", hasHeaderAssetCandidate ? "input_asset_or_image2_asset_downstream_only" : "image2_asset_or_neutral_placeholder") .attr("data-anchor", "upper-left-header-safe-area") .attr("data-collision-rule", "stay left of title/subtitle and above chart panel; do not overlap title, subtitle, legend, or bars") .attr("data-bbox", `${headerArt.x},${headerArt.y},${headerArt.w},${headerArt.h}`) .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true"); artSlot.append("rect") .attr("x", headerArt.x + 32) .attr("y", headerArt.y + 48) .attr("width", headerArt.w - 64) .attr("height", headerArt.h - 96) .attr("rx", 20) .attr("fill", "#F6FAFF") .attr("stroke", "#BCD0EC") .attr("stroke-width", 2) .attr("stroke-dasharray", "9 9") .attr("opacity", 0.82); artSlot.append("circle") .attr("cx", headerArt.x + headerArt.w / 2) .attr("cy", headerArt.y + headerArt.h / 2) .attr("r", 34) .attr("fill", "none") .attr("stroke", "#D1DDF0") .attr("stroke-width", 2) .attr("opacity", 0.9);
const titleFamily = (typography.title && typography.title.font_family) || "Arial, Helvetica, sans-serif"; const titleFontSize = 44; const titleLines = wrapLines(titleText, titleBox.w, titleFontSize, 900, 2, titleFamily); const titleEl = svg.append("text") .attr("class", "title") .attr("x", titleBox.x) .attr("y", titleBox.y) .attr("text-anchor", "start") .style("font-family", titleFamily) .style("font-size", `${titleFontSize}px`) .style("font-weight", 900) .style("fill", titleColor) .style("letter-spacing", "0"); titleLines.forEach((line, i) => { titleEl.append("tspan") .attr("x", titleBox.x) .attr("dy", i === 0 ? 0 : "1.1em") .text(line); }); const ruleY = titleBox.y + Math.min(158, titleLines.length * (titleFontSize * 1.1) + 16); svg.append("line") .attr("x1", titleBox.x + 4) .attr("x2", titleBox.x + 374) .attr("y1", ruleY) .attr("y2", ruleY) .attr("stroke", leftColor) .attr("stroke-width", 4) .attr("stroke-linecap", "round"); svg.append("line") .attr("x1", titleBox.x + 316) .attr("x2", titleBox.x + 436) .attr("y1", ruleY) .attr("y2", ruleY) .attr("stroke", rightColor) .attr("stroke-width", 4) .attr("stroke-linecap", "round"); addWrappedText(svg, subtitleText, titleBox.x + 4, ruleY + 36, titleBox.w - 28, { fontFamily: "Arial, Helvetica, sans-serif", fontSize: 25, fontWeight: 400, fill: mutedText, maxLines: 3, lineHeight: 1.3 });
const legendY = ruleY + 140; function addLegendItem(x, group, color) { svg.append("circle") .attr("cx", x) .attr("cy", legendY) .attr("r", 13) .attr("fill", color); svg.append("text") .attr("x", x + 28) .attr("y", legendY + 7) .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", "22px") .style("font-weight", 500) .style("fill", "#151B26") .text(humanize(group)); } addLegendItem(titleBox.x + 8, leftGroup, leftColor); addLegendItem(titleBox.x + 258, rightGroup, rightColor); svg.append("line") .attr("x1", titleBox.x + 226) .attr("x2", titleBox.x + 226) .attr("y1", legendY - 20) .attr("y2", legendY + 24) .attr("stroke", "#C6CCD7") .attr("stroke-width", 1.5);
const panel = { x: 42, y: 455, w: 940, h: 965 }; svg.append("rect") .attr("class", "chart-panel") .attr("x", panel.x) .attr("y", panel.y) .attr("width", panel.w) .attr("height", panel.h) .attr("rx", 28) .attr("fill", "#FFFFFF") .attr("filter", "url(#hdbc04hand-soft-shadow)") .attr("opacity", 0.98);
const inner = { x: panel.x + 48, y: panel.y + 92, w: panel.w - 96, h: panel.h - 155 }; const leftInnerX = panel.x + 390; const rightInnerX = panel.x + 560; const leftOuterMin = panel.x + 128; const rightOuterMax = panel.x + panel.w - 132; const iconX = panel.x + panel.w / 2; const rowBand = inner.h / rowCount; const rowGap = Math.max(6, Math.min(14, rowBand * 0.14)); const barH = Math.max(23, Math.min(58, rowBand - rowGap)); const chipR = Math.max(17, Math.min(29, barH * 0.50)); const leftMax = d3.max(rowsRaw.filter(d => d[groupField] === leftGroup), d => +d[valueField] || 0) || 1; const rightMax = d3.max(rowsRaw.filter(d => d[groupField] === rightGroup), d => +d[valueField] || 0) || 1; const leftScale = d3.scaleLinear().domain([0, leftMax]).range([0, leftInnerX - leftOuterMin]); const rightScale = d3.scaleLinear().domain([0, rightMax]).range([0, rightOuterMax - rightInnerX]);
function addHeaderPill(group, x, y, color) { const label = String(group || "").toUpperCase(); const pillW = Math.min(260, Math.max(150, measure(label, 24, 900) + 54)); const pill = svg.append("g") .attr("class", "group-header") .attr("data-group", String(group)) .attr("data-anchor", "bar-subcolumn-center") .attr("data-coordinate-rule", "centerline-aligned-to-side-bar-column"); pill.append("rect") .attr("x", x - pillW / 2) .attr("y", y - 33) .attr("width", pillW) .attr("height", 52) .attr("rx", 14) .attr("fill", color); pill.append("text") .attr("x", x) .attr("y", y + 2) .attr("text-anchor", "middle") .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", label.length > 15 ? "18px" : "24px") .style("font-weight", 900) .style("fill", "#FFFFFF") .text(label); } addHeaderPill(leftGroup, panel.x + 260, panel.y + 58, leftColor); addHeaderPill(rightGroup, panel.x + 704, panel.y + 58, rightColor);
rowData.forEach((row, index) => { const y0 = inner.y + index * rowBand; if (index > 0) { svg.append("line") .attr("class", "row-separator") .attr("x1", panel.x + 24) .attr("x2", panel.x + panel.w - 24) .attr("y1", y0) .attr("y2", y0) .attr("stroke", "#E5EAF2") .attr("stroke-width", 1.2) .attr("stroke-dasharray", "5 5") .attr("opacity", 0.86); } });
function roundedBarPath(xInner, y, barWidth, h, side) { const r = Math.min(6, h * 0.12, Math.max(2, barWidth / 2)); if (side === "left") { const xOuter = xInner - barWidth; return [ `M ${xInner} ${y + r}`, `Q ${xInner} ${y} ${xInner - r} ${y}`, `L ${xOuter + r} ${y}`, `Q ${xOuter} ${y} ${xOuter} ${y + r}`, `L ${xOuter} ${y + h - r}`, `Q ${xOuter} ${y + h} ${xOuter + r} ${y + h}`, `L ${xInner - r} ${y + h}`, `Q ${xInner} ${y + h} ${xInner} ${y + h - r}`, "Z" ].join(" "); } const xOuter = xInner + barWidth; return [ `M ${xInner} ${y + r}`, `Q ${xInner} ${y} ${xInner + r} ${y}`, `L ${xOuter - r} ${y}`, `Q ${xOuter} ${y} ${xOuter} ${y + r}`, `L ${xOuter} ${y + h - r}`, `Q ${xOuter} ${y + h} ${xOuter - r} ${y + h}`, `L ${xInner + r} ${y + h}`, `Q ${xInner} ${y + h} ${xInner} ${y + h - r}`, "Z" ].join(" "); }
function addValueLabel(value, x, cy, side, barWidth) { const text = formatValue(value); const fontSize = Math.max(24, Math.min(34, barH * 0.66)); const textW = measure(text, fontSize, 900); let labelX; let anchor; if (side === "left") { labelX = Math.max(panel.x + 60 + textW, x - 18); anchor = "end"; if (labelX > x - 12) labelX = x - 12; } else { labelX = Math.min(panel.x + panel.w - 38 - textW, x + 18); anchor = "start"; } svg.append("text") .attr("class", `value-label ${side}-value-label`) .attr("x", labelX) .attr("y", cy) .attr("dy", "0.35em") .attr("text-anchor", anchor) .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", `${fontSize}px`) .style("font-weight", 900) .style("fill", side === "left" ? leftColor : rightColor) .style("letter-spacing", "0") .text(text); }
function addCategorySlot(row, cy) { const dimension = row.dimension; const slot = svg.append("g") .attr("class", "asset-slot category-icon-slot") .attr("data-asset-slot", "category-icon") .attr("data-category", String(dimension)) .attr("data-asset-source-policy", hasCategoryAssetCandidate(dimension) ? "input_asset_or_retrieval_downstream_only" : "neutral_placeholder") .attr("data-anchor", "row-centerline-central-label-column") .attr("data-collision-rule", "stay inside central label column; avoid flat bar inner edges and value labels") .attr("data-bbox", `${(iconX - chipR).toFixed(1)},${(cy - chipR).toFixed(1)},${(chipR * 2).toFixed(1)},${(chipR * 2).toFixed(1)}`) .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true"); slot.append("circle") .attr("cx", iconX) .attr("cy", cy) .attr("r", chipR) .attr("fill", "#FFFFFF") .attr("stroke", "#E3E9F2") .attr("stroke-width", 1.4) .attr("filter", "url(#hdbc04hand-soft-shadow)"); slot.append("circle") .attr("cx", iconX) .attr("cy", cy) .attr("r", Math.max(4, chipR * 0.18)) .attr("fill", "#DDE7F5") .attr("opacity", 0.95); }
rowData.forEach(row => { const cy = inner.y + row.index * rowBand + rowBand / 2; const y = cy - barH / 2; const leftValue = row.left ? +row.left[valueField] || 0 : 0; const rightValue = row.right ? +row.right[valueField] || 0 : 0; const leftW = leftValue > 0 ? Math.max(4, leftScale(leftValue)) : 0; const rightW = rightValue > 0 ? Math.max(4, rightScale(rightValue)) : 0; if (leftW > 0) { svg.append("path") .attr("class", "bar left-bar") .attr("d", roundedBarPath(leftInnerX, y, leftW, barH, "left")) .attr("fill", "url(#hdbc04hand-left-bar)") .attr("data-category", String(row.dimension)) .attr("data-group", String(leftGroup)) .attr("data-value", leftValue) .attr("data-cap-geometry", "small-radius-rounded-inner-and-outer-edges"); } if (rightW > 0) { svg.append("path") .attr("class", "bar right-bar") .attr("d", roundedBarPath(rightInnerX, y, rightW, barH, "right")) .attr("fill", "url(#hdbc04hand-right-bar)") .attr("data-category", String(row.dimension)) .attr("data-group", String(rightGroup)) .attr("data-value", rightValue) .attr("data-cap-geometry", "small-radius-rounded-inner-and-outer-edges"); } addValueLabel(leftValue, leftInnerX - leftW, cy, "left", leftW); addValueLabel(rightValue, rightInnerX + rightW, cy, "right", rightW); addCategorySlot(row, cy); const labelText = humanize(row.dimension); const labelMaxWidth = Math.max(112, rightInnerX - leftInnerX - chipR * 2 - 10); let fontSize = Math.max(13, Math.min(18, rowBand * 0.20)); let labelLines = wrapLines(labelText, labelMaxWidth, fontSize, 700, 2, "Arial, Helvetica, sans-serif"); if (labelLines.length > 1) { fontSize = Math.max(12, fontSize - 2); labelLines = wrapLines(labelText, labelMaxWidth, fontSize, 700, 2, "Arial, Helvetica, sans-serif"); } const firstLineY = cy + chipR + (labelLines.length > 1 ? 8 : 16); const label = svg.append("text") .attr("class", "category-label") .attr("x", iconX) .attr("y", firstLineY) .attr("text-anchor", "middle") .style("font-family", "Arial, Helvetica, sans-serif") .style("font-size", `${fontSize}px`) .style("font-weight", 700) .style("fill", "#141A24") .style("letter-spacing", "0"); labelLines.forEach((line, i) => { label.append("tspan") .attr("x", iconX) .attr("dy", i === 0 ? 0 : "1.02em") .text(line); }); });
svg.append("g") .attr("class", "ignored-bottom-wrapper-policy") .attr("data-ignored-element", "bottom_takeaway_source_footer") .attr("data-policy", "not-rendered");
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Diverging Bar Chart", "chart_name": "horizontal_diverging_bar_chart_05", "chart_for": "comparison", "is_composite": false, "required_fields": ["x", "y", "group"], "required_fields_type": [["categorical"], ["numerical"], ["categorical"]], "required_fields_range": [[2, 20], [0, "inf"], [2, 2]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": ["group"], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "styled", "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 && jsonData.data.data) || []; const variables = jsonData.variables || {}; const typography = jsonData.typography || { title: { font_family: "Georgia", font_size: "32px", font_weight: 700 }, label: { font_family: "Arial", font_size: "14px", font_weight: 500 }, description: { font_family: "Arial", font_size: "15px", font_weight: 400 }, annotation: { font_family: "Arial", font_size: "13px", font_weight: 500 } }; const colorResolver = chartUtils.color.resolver(jsonData); const width = Math.max(720, +variables.width || 1024); const height = Math.max(920, +variables.height || 1536);
d3.select(containerSelector).html(""); 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");
const defs = svg.append("defs"); const bgGradient = defs.append("radialGradient") .attr("id", "hdbar05-bg") .attr("cx", "50%") .attr("cy", "18%") .attr("r", "85%"); bgGradient.append("stop").attr("offset", "0%").attr("stop-color", "#FFFDF6"); bgGradient.append("stop").attr("offset", "72%").attr("stop-color", "#F7F0E3"); bgGradient.append("stop").attr("offset", "100%").attr("stop-color", "#EFE2CD");
const shadow = defs.append("filter") .attr("id", "hdbar05-soft-shadow") .attr("x", "-20%") .attr("y", "-35%") .attr("width", "150%") .attr("height", "190%"); shadow.append("feDropShadow") .attr("dx", "0") .attr("dy", "7") .attr("stdDeviation", "5") .attr("flood-color", "#1E2A31") .attr("flood-opacity", "0.20");
const leftBase = "#0F6B3B"; const rightBase = "#1F63B7"; const leftColor = d3.color(leftBase) ? d3.color(leftBase).formatHex() : "#0F6B3B"; const rightColor = d3.color(rightBase) ? d3.color(rightBase).formatHex() : "#1C5FB5";
function gradient(id, color, darkenAmount) { const base = d3.color(color); const hi = base ? base.brighter(0.65).formatHex() : color; const lo = base ? base.darker(darkenAmount).formatHex() : color; const g = defs.append("linearGradient").attr("id", id).attr("x1", "0%").attr("x2", "100%").attr("y1", "0%").attr("y2", "0%"); g.append("stop").attr("offset", "0%").attr("stop-color", hi); g.append("stop").attr("offset", "58%").attr("stop-color", color); g.append("stop").attr("offset", "100%").attr("stop-color", lo); } gradient("hdbar05-left-gradient", leftColor, 0.9); gradient("hdbar05-right-gradient", rightColor, 0.75);
svg.append("rect").attr("width", width).attr("height", height).attr("fill", "url(#hdbar05-bg)");
const schemaX = chartUtils.schema.channel(jsonData, "x"); const schemaY = chartUtils.schema.channel(jsonData, "y"); const schemaGroup = chartUtils.schema.channel(jsonData, "group"); const dimensionField = schemaX.key; const valueField = schemaY.key; const groupField = schemaGroup.key; const valueUnit = schemaY.unit && schemaY.unit !== "none" ? schemaY.unit : ""; const groupUnit = schemaGroup.unit && schemaGroup.unit !== "none" ? schemaGroup.unit : ""; const dimensionUnit = schemaX.unit && schemaX.unit !== "none" ? schemaX.unit : "";
function isTemporalField() { const col = (chartUtils.schema.columns(jsonData) || []).find(c => c.name === dimensionField) || {}; return /date|time|year|month|season|semester|quarter/i.test(`${dimensionField} ${col.description || ""} ${col.data_type || ""}`); }
const monthMap = { 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, september: 9, oct: 10, october: 10, nov: 11, november: 11, dec: 12, december: 12 };
function temporalKey(value) { if (value instanceof Date) return value.getTime(); if (typeof value === "number" && Number.isFinite(value)) return value; const text = String(value || "").trim(); const lower = text.toLowerCase(); if (/^-?\d+(\.\d+)?$/.test(text)) return +text; if (monthMap[lower]) return monthMap[lower]; const quarter = lower.match(/q([1-4])\s*[- ]?\s*(\d{2,4})?|\b(\d{2,4})\s*q([1-4])\b/); if (quarter) { const q = +(quarter[1] || quarter[4]); const year = +(quarter[2] || quarter[3] || 0); return year * 10 + q; } const parsed = Date.parse(text); return Number.isNaN(parsed) ? null : parsed; }
const temporalDimension = isTemporalField(); const rawDimensions = [...new Set(chartData.map(d => d[dimensionField]))]; const dimensions = rawDimensions.slice(); if (temporalDimension) { dimensions.sort((a, b) => { const ak = temporalKey(a); const bk = temporalKey(b); if (ak == null || bk == null) return rawDimensions.indexOf(a) - rawDimensions.indexOf(b); return ak - bk; }); } const groups = [...new Set(chartData.map(d => d[groupField]))].slice(0, 2); const leftGroup = groups[0] || "Left"; const rightGroup = groups[1] || "Right"; const leftGroupText = groupUnit ? `${leftGroup}${groupUnit}` : `${leftGroup}`; const rightGroupText = groupUnit ? `${rightGroup}${groupUnit}` : `${rightGroup}`;
const byKey = new Map(); chartData.forEach(d => byKey.set(`${d[dimensionField]}|||${d[groupField]}`, d)); const maxValue = Math.max(1, d3.max(chartData, d => +d[valueField]) || 1); const axisMax = maxValue <= 100 ? 100 : Math.ceil(maxValue / 10) * 10; const ticks = d3.range(0, axisMax + 0.1, axisMax / 5);
function splitTitle(title) { const words = String(title || "").trim().split(/\s+/).filter(Boolean); const stabilityIndex = words.findIndex(w => /^stability/i.test(w)); const indexIndex = words.findIndex(w => /^index/i.test(w)); if (stabilityIndex > 0 && indexIndex > stabilityIndex) { const first = words.slice(0, indexIndex).join(" "); const overIndex = words.findIndex((w, i) => i > indexIndex && /^over$/i.test(w)); const secondTail = overIndex > indexIndex ? "" : words.slice(stabilityIndex + 1, indexIndex).join(" "); const second = secondTail; const banner = words.slice(indexIndex).join(" "); return { first, second, banner }; } return { first: words.slice(0, Math.max(2, Math.ceil(words.length / 2))).join(" "), second: words.slice(Math.max(2, Math.ceil(words.length / 2))).join(" "), banner: words.slice(Math.max(1, Math.floor(words.length / 2))).join(" ") }; }
function fitText(selection, maxWidth, minSize) { selection.each(function() { const node = d3.select(this); let size = parseFloat(node.style("font-size")) || parseFloat(node.attr("font-size")) || 20; while (this.getComputedTextLength && this.getComputedTextLength() > maxWidth && size > minSize) { size -= 1; node.style("font-size", `${size}px`).attr("font-size", size); } }); }
function estimatedTextWidth(text, fontSize) { return String(text || "").length * fontSize * 0.58; }
function ellipsizeToWidth(text, maxWidth, fontSize) { const raw = String(text || ""); if (estimatedTextWidth(raw, fontSize) <= maxWidth) return raw; const maxChars = Math.max(4, Math.floor(maxWidth / (fontSize * 0.58))); if (maxChars <= 4) return raw.slice(0, Math.max(1, maxChars - 1)) + "..."; return raw.slice(0, maxChars - 3).replace(/[.,;: _-]+$/, "") + "..."; }
function wrapLines(text, maxChars, maxLines) { const words = String(text || "").split(/\s+/).filter(Boolean); const lines = []; let current = ""; words.forEach(word => { const trial = current ? `${current} ${word}` : word; if (current && trial.length > maxChars && lines.length < maxLines - 1) { lines.push(current); current = word; } else { current = trial; } }); if (current) lines.push(current); if (lines.length > maxLines) { const kept = lines.slice(0, maxLines); kept[maxLines - 1] = `${kept[maxLines - 1].replace(/[.,;: ]+$/, "")}...`; return kept; } return lines; }
const title = (jsonData.titles && jsonData.titles.main_title) || (jsonData.metadata && jsonData.metadata.title) || ""; const subtitle = (jsonData.titles && jsonData.titles.sub_title) || (jsonData.metadata && jsonData.metadata.description) || ""; const titleParts = splitTitle(title);
const gold = "#C59432"; const darkGreen = "#0E482A"; const navy = "#132334"; const chartLeft = width * 0.095; const chartRight = width * 0.92; const centerX = width * 0.50; const rowTop = height * 0.378; const rowBottom = height * 0.810; const rowBand = (rowBottom - rowTop) / Math.max(1, dimensions.length); const barHeight = Math.max(28, Math.min(58, rowBand * 0.62)); const yearGap = width * 0.108; const leftAxisStart = width * 0.115; const labelFontForLayout = Math.max(15, Math.min(29, rowBand * 0.42)); const maxLeftValueLabelWidth = d3.max(dimensions, dimension => { const row = byKey.get(`${dimension}|||${leftGroup}`); if (!row) return 0; return String(formatValue(Math.max(0, +row[valueField] || 0))).length * labelFontForLayout * 0.70; }) || 0; const maxRightValueLabelWidth = d3.max(dimensions, dimension => { const row = byKey.get(`${dimension}|||${rightGroup}`); if (!row) return 0; return String(formatValue(Math.max(0, +row[valueField] || 0))).length * labelFontForLayout * 0.70; }) || 0; const centerPillMaxW = temporalDimension ? Math.max(70, Math.min(92, yearGap * 0.78)) : Math.max(82, Math.min(112, yearGap * 0.98)); const nominalLeftAxisEnd = centerX - yearGap * 0.72; const leftValueLabelSafeRight = centerX - Math.max(36, yearGap * 0.34); const leftAxisEnd = Math.max( leftAxisStart + width * 0.21, Math.min(nominalLeftAxisEnd, leftValueLabelSafeRight - maxLeftValueLabelWidth - 12) ); const nominalRightAxisStart = centerX + yearGap * 1.08; const rightValueLabelSafeLeft = Math.max( centerX + Math.max(32, yearGap * 0.30), centerX + centerPillMaxW / 2 + 18 ); const rightAxisStart = Math.min( chartRight - width * 0.22, Math.max(nominalRightAxisStart, rightValueLabelSafeLeft + maxRightValueLabelWidth + 24) ); const rowCardHeight = Math.max(barHeight + 14, Math.min(rowBand * 0.78, 66)); const rowCardRadius = Math.min(16, rowCardHeight * 0.28); const rowIconRadius = Math.max(13, Math.min(25, rowCardHeight * 0.40)); const leftRowCardX = width * 0.038; const leftRowCardW = Math.max(leftAxisEnd + width * 0.018, leftValueLabelSafeRight + 8) - leftRowCardX; const rightRowCardX = Math.min(rightAxisStart - width * 0.018, centerX + yearGap * 0.52); const rightRowCardW = (width * 0.966) - rightRowCardX; const leftRowIconX = leftRowCardX + rowIconRadius + width * 0.010; const rightRowIconX = rightRowCardX + rightRowCardW - rowIconRadius - width * 0.010; const rightSlotClearance = Math.max(18, width * 0.022); const rightAxisEnd = Math.min(chartRight, rightRowIconX - rowIconRadius - rightSlotClearance); const leftScale = d3.scaleLinear().domain([0, axisMax]).range([0, leftAxisEnd - leftAxisStart]); const rightScale = d3.scaleLinear().domain([0, axisMax]).range([0, rightAxisEnd - rightAxisStart]); const rowCenter = d => rowTop + dimensions.indexOf(d) * rowBand + rowBand / 2;
function titleOrnament(cx, cy) { const slot = svg.append("g") .attr("class", "reserved-asset-slot hdbar05-title-ornament-slot") .attr("data-asset-slot", "title-ornament") .attr("data-slot-policy", "image2_asset_or_neutral_placeholder") .attr("data-asset-source-policy", "image2_asset") .attr("data-anchor", "top-center-above-title") .attr("data-collision-rule", "stay outside title/subtitle glyphs and above chart panel") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true"); slot.append("line").attr("x1", cx - 18).attr("x2", cx + 18).attr("y1", cy).attr("y2", cy).attr("stroke", gold).attr("stroke-width", 5).attr("stroke-linecap", "round"); slot.append("line").attr("x1", cx).attr("x2", cx).attr("y1", cy - 18).attr("y2", cy + 18).attr("stroke", gold).attr("stroke-width", 5).attr("stroke-linecap", "round"); slot.append("circle").attr("cx", cx).attr("cy", cy).attr("r", 5).attr("fill", "#F6E0A0").attr("stroke", gold).attr("stroke-width", 1.2); }
titleOrnament(centerX, height * 0.055); svg.append("line").attr("x1", width * 0.19).attr("x2", width * 0.45).attr("y1", height * 0.075).attr("y2", height * 0.075).attr("stroke", gold).attr("stroke-width", 1.6); svg.append("line").attr("x1", width * 0.55).attr("x2", width * 0.81).attr("y1", height * 0.075).attr("y2", height * 0.075).attr("stroke", gold).attr("stroke-width", 1.6); svg.append("circle").attr("cx", width * 0.19).attr("cy", height * 0.075).attr("r", 4).attr("fill", gold); svg.append("circle").attr("cx", width * 0.81).attr("cy", height * 0.075).attr("r", 4).attr("fill", gold);
const titleGroup = svg.append("g").attr("class", "hdbar05-title-block"); const titleFirst = titleGroup.append("text") .attr("x", centerX) .attr("y", height * 0.137) .attr("text-anchor", "middle") .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", width * 0.058) .attr("font-weight", 700) .attr("letter-spacing", "0") .attr("fill", darkGreen) .text((titleParts.first || title).toUpperCase()); fitText(titleFirst, width * 0.86, 34);
if (titleParts.second) { const second = titleGroup.append("text") .attr("x", centerX) .attr("y", height * 0.178) .attr("text-anchor", "middle") .attr("font-family", "Arial, Helvetica, sans-serif") .attr("font-size", width * 0.033) .attr("font-weight", 500) .attr("letter-spacing", "10") .attr("fill", navy) .text(titleParts.second.toUpperCase()); fitText(second, width * 0.74, 18); }
const bannerW = width * 0.84; const bannerH = height * 0.056; const bannerY = titleParts.second ? height * 0.205 : height * 0.182; const notch = bannerH * 0.32; const bannerX = centerX - bannerW / 2; const bannerPath = [ `M${bannerX + notch},${bannerY}`, `L${bannerX + bannerW - notch},${bannerY}`, `L${bannerX + bannerW},${bannerY + bannerH / 2}`, `L${bannerX + bannerW - notch},${bannerY + bannerH}`, `L${bannerX + notch},${bannerY + bannerH}`, `L${bannerX},${bannerY + bannerH / 2}`, "Z" ].join(" "); titleGroup.append("path") .attr("d", bannerPath) .attr("fill", "#064A2A") .attr("stroke", "#15351F") .attr("stroke-width", 3) .attr("filter", "url(#hdbar05-soft-shadow)"); titleGroup.append("path") .attr("d", bannerPath) .attr("fill", "none") .attr("stroke", "#F8FAF1") .attr("stroke-width", 2) .attr("opacity", 0.92); const bannerText = titleGroup.append("text") .attr("x", centerX) .attr("y", bannerY + bannerH * 0.68) .attr("text-anchor", "middle") .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", bannerH * 0.56) .attr("font-weight", 800) .attr("letter-spacing", "1.2") .attr("fill", "#FFFFFF") .text((titleParts.banner || title).toUpperCase()); fitText(bannerText, bannerW * 0.83, Math.max(26, bannerH * 0.38));
const subtitleLines = wrapLines(subtitle, 74, 2); const subtitleFontSize = subtitleLines.length > 1 ? width * 0.019 : width * 0.021; const subtitleLineGap = subtitleLines.length > 1 ? 27 : 34; const subtitleStartY = bannerY + bannerH + height * 0.020; subtitleLines.forEach((line, i) => { svg.append("text") .attr("x", centerX) .attr("y", subtitleStartY + i * subtitleLineGap) .attr("text-anchor", "middle") .attr("font-family", "Arial, Helvetica, sans-serif") .attr("font-size", subtitleFontSize) .attr("font-weight", 400) .attr("fill", "#262D34") .text(line); });
function medallionSlot(cx, cy, color, side) { const r = width * 0.039; const slot = svg.append("g") .attr("class", `reserved-asset-slot hdbar05-group-medallion-slot ${side}`) .attr("data-asset-slot", `${side}-group-medallion`) .attr("data-slot-policy", "image2_asset_or_input_asset_or_neutral_placeholder") .attr("data-asset-source-policy", "image2_asset_or_input_asset") .attr("data-anchor", `${side}-group-header`) .attr("data-collision-rule", "stay adjacent to group header and outside bar/value/year-label rows") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-bbox", `${(cx - r).toFixed(1)},${(cy - r).toFixed(1)},${(r * 2).toFixed(1)},${(r * 2).toFixed(1)}`); slot.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", r) .attr("fill", color) .attr("stroke", "#E6C46C") .attr("stroke-width", 3); slot.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", r * 0.76) .attr("fill", "none") .attr("stroke", "#F5E4A2") .attr("stroke-width", 2) .attr("opacity", 0.80); slot.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", r * 0.18) .attr("fill", "none") .attr("stroke", "#F5E4A2") .attr("stroke-width", 2) .attr("opacity", 0.78); }
const headerY = height * 0.325; const headerPillH = Math.max(44, Math.min(58, rowBand * 0.78)); const leftMedallionX = width * 0.132; const rightMedallionX = width * 0.585; const leftPillX = leftMedallionX + width * 0.020; const rightPillX = rightMedallionX + width * 0.020; const leftPillW = width * 0.305; const rightPillW = width * 0.330; svg.append("rect") .attr("class", "hdbar05-group-label-pill left") .attr("x", leftPillX) .attr("y", headerY - headerPillH / 2) .attr("width", leftPillW) .attr("height", headerPillH) .attr("rx", 7) .attr("fill", "#F2F4EA") .attr("stroke", leftColor) .attr("stroke-width", 1.2) .attr("opacity", 0.92); svg.append("rect") .attr("class", "hdbar05-group-label-pill right") .attr("x", rightPillX) .attr("y", headerY - headerPillH / 2) .attr("width", rightPillW) .attr("height", headerPillH) .attr("rx", 7) .attr("fill", "#F1F4F8") .attr("stroke", rightColor) .attr("stroke-width", 1.2) .attr("opacity", 0.92); medallionSlot(leftMedallionX, headerY, leftColor, "left"); medallionSlot(rightMedallionX, headerY, rightColor, "right"); const leftHeader = svg.append("text") .attr("x", leftPillX + width * 0.050) .attr("y", headerY + 10) .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", width * 0.031) .attr("font-weight", 700) .attr("fill", darkGreen) .text(leftGroupText); fitText(leftHeader, leftPillW - width * 0.070, 18); const rightHeader = svg.append("text") .attr("x", rightPillX + width * 0.050) .attr("y", headerY + 10) .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", width * 0.031) .attr("font-weight", 700) .attr("fill", rightColor) .text(rightGroupText); fitText(rightHeader, rightPillW - width * 0.070, 18);
function measureHeader(value) { const words = String(value || "") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/[_-]+/g, " ") .trim() .split(/\s+/) .filter(Boolean); if (!words.length) return "VALUE"; return words.join(" ").toUpperCase(); }
const columnHeaderY = rowTop - rowBand * 0.42; const leftMeasureHeader = svg.append("text") .attr("class", "hdbar05-column-measure-header left") .attr("x", (leftAxisStart + leftAxisEnd) / 2) .attr("y", columnHeaderY) .attr("text-anchor", "middle") .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", Math.max(14, Math.min(18, rowBand * 0.25))) .attr("font-weight", 800) .attr("letter-spacing", "0.6") .attr("fill", darkGreen) .text(measureHeader(valueField)); fitText(leftMeasureHeader, leftAxisEnd - leftAxisStart, 11);
const rightMeasureHeader = svg.append("text") .attr("class", "hdbar05-column-measure-header right") .attr("x", (rightAxisStart + rightAxisEnd) / 2) .attr("y", columnHeaderY) .attr("text-anchor", "middle") .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", Math.max(14, Math.min(18, rowBand * 0.25))) .attr("font-weight", 800) .attr("letter-spacing", "0.6") .attr("fill", rightColor) .text(measureHeader(valueField)); fitText(rightMeasureHeader, rightAxisEnd - rightAxisStart, 11);
svg.append("text") .attr("class", "hdbar05-center-header") .attr("x", centerX) .attr("y", columnHeaderY) .attr("text-anchor", "middle") .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", Math.max(14, Math.min(19, rowBand * 0.27))) .attr("font-weight", 800) .attr("letter-spacing", "0.3") .attr("fill", "#1B2C22") .text(temporalDimension ? "YEAR" : compactHeader(dimensionField));
svg.append("line") .attr("x1", centerX) .attr("x2", centerX) .attr("y1", rowTop - rowBand * 0.16) .attr("y2", rowBottom + rowBand * 0.16) .attr("stroke", darkGreen) .attr("stroke-width", 3) .attr("opacity", 0.72) .attr("stroke-linecap", "round");
function barPath(x, y, w, h) { const c = Math.max(0, Math.min(8, h * 0.18, w * 0.18)); return [ `M${x},${y}`, `L${x + w - c},${y}`, `L${x + w},${y + c}`, `L${x + w},${y + h - c}`, `L${x + w - c},${y + h}`, `L${x},${y + h}`, "Z" ].join(" "); }
function formatValue(v) { return valueUnit ? `${chartUtils.format.autoText(+v)}${valueUnit}` : `${chartUtils.format.autoText(+v)}`; }
function valueLabelPlacement(text, barWidth, fontSize, inset) { const estimatedTextWidth = String(text || "").length * fontSize * 0.62; return barWidth >= estimatedTextWidth + inset + 8; }
function slotId(value) { return String(value || "row") .toLowerCase() .replace(/[^a-z0-9]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 48) || "row"; }
function compactHeader(value) { const words = String(value || "") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/[_-]+/g, " ") .trim() .split(/\s+/) .filter(Boolean); if (!words.length) return "LABEL"; const picked = words.length > 1 ? words[words.length - 1] : words[0]; return picked.slice(0, 10).toUpperCase(); }
const rowLayer = svg.append("g").attr("class", "hdbar05-row-card-layer");
function rowCardAndIcon(side, dimension, formattedDimension, cy, color) { const x = side === "left" ? leftRowCardX : rightRowCardX; const w = side === "left" ? leftRowCardW : rightRowCardW; const iconCx = side === "left" ? leftRowIconX : rightRowIconX; const cardY = cy - rowCardHeight / 2; const safeDimension = slotId(formattedDimension); const slot = rowLayer.append("g") .attr("class", `hdbar05-row-card-with-icon ${side}`) .attr("data-dimension", formattedDimension) .attr("data-anchor", `row-${safeDimension}-${side}-container`) .attr("data-relationship", "row-card-span-matched-to-bar-row-centerline");
slot.append("rect") .attr("class", `row-card ${side}`) .attr("x", x) .attr("y", cardY) .attr("width", w) .attr("height", rowCardHeight) .attr("rx", rowCardRadius) .attr("fill", side === "left" ? "#F1F2E8" : "#EEF2F6") .attr("stroke", side === "left" ? "#DDE6D5" : "#DCE5F0") .attr("stroke-width", 1) .attr("opacity", 0.88);
const icon = slot.append("g") .attr("class", `reserved-asset-slot hdbar05-row-icon-slot ${side}`) .attr("data-asset-slot", `${side}-row-icon-${safeDimension}`) .attr("data-slot-policy", "input_asset_or_image2_asset_or_neutral_placeholder") .attr("data-asset-source-policy", "input_asset_or_image2_asset") .attr("data-dimension", formattedDimension) .attr("data-group", side === "left" ? leftGroupText : rightGroupText) .attr("data-anchor", `row-${safeDimension}-${side}-card-centerline`) .attr("data-collision-rule", "stay inside the row card, outside bar/value labels/year-axis text, and share the row centerline") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-bbox", `${(iconCx - rowIconRadius).toFixed(1)},${(cy - rowIconRadius).toFixed(1)},${(rowIconRadius * 2).toFixed(1)},${(rowIconRadius * 2).toFixed(1)}`);
icon.append("circle") .attr("cx", iconCx) .attr("cy", cy) .attr("r", rowIconRadius) .attr("fill", side === "left" ? "#E7EFDF" : "#E8EEF6") .attr("stroke", "#FFFFFF") .attr("stroke-width", 2) .attr("opacity", 0.96); icon.append("circle") .attr("cx", iconCx) .attr("cy", cy) .attr("r", Math.max(5, rowIconRadius * 0.28)) .attr("fill", "none") .attr("stroke", color) .attr("stroke-width", 2) .attr("opacity", 0.72); }
dimensions.forEach((dimension) => { const cy = rowCenter(dimension); const y = cy - barHeight / 2; const formattedDimension = dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}`;
rowCardAndIcon("left", dimension, formattedDimension, cy, leftColor); rowCardAndIcon("right", dimension, formattedDimension, cy, rightColor);
const centerPillW = centerPillMaxW; const centerPillH = temporalDimension ? Math.max(30, Math.min(38, rowBand * 0.56)) : Math.max(24, Math.min(34, rowBand * 0.48)); const dimensionFont = temporalDimension ? Math.max(17, Math.min(25, centerPillH * 0.62)) : Math.max(9, Math.min(14, centerPillH * 0.42)); const displayDimension = temporalDimension ? formattedDimension : ellipsizeToWidth(formattedDimension, centerPillW - 13, dimensionFont);
svg.append("rect") .attr("class", "hdbar05-center-label-pill") .attr("data-dimension", formattedDimension) .attr("data-relationship", "centerline-aligned-to-vertical-spine") .attr("x", centerX - centerPillW / 2) .attr("y", cy - centerPillH / 2) .attr("width", centerPillW) .attr("height", centerPillH) .attr("rx", Math.min(10, centerPillH * 0.34)) .attr("fill", darkGreen) .attr("stroke", "#F3E2A7") .attr("stroke-width", 1.1);
const dimensionText = svg.append("text") .attr("class", "hdbar05-center-label-text") .attr("data-full-label", formattedDimension) .attr("x", centerX) .attr("y", cy + dimensionFont * 0.36) .attr("text-anchor", "middle") .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", dimensionFont) .attr("font-weight", 700) .attr("fill", "#FFFFFF") .text(displayDimension); fitText(dimensionText, centerPillW - 12, temporalDimension ? 14 : 8);
const leftData = byKey.get(`${dimension}|||${leftGroup}`); const rightData = byKey.get(`${dimension}|||${rightGroup}`); if (leftData) { const v = Math.max(0, +leftData[valueField] || 0); const w = Math.max(2, leftScale(v)); const x = leftAxisStart; const labelText = formatValue(v); const labelFontSize = Math.max(15, Math.min(29, rowBand * 0.42)); svg.append("path") .attr("class", "bar left-bar") .attr("data-dimension", formattedDimension) .attr("data-group", leftGroupText) .attr("data-value", v) .attr("d", barPath(x, y, w, barHeight)) .attr("fill", "url(#hdbar05-left-gradient)") .attr("stroke", d3.color(leftColor).darker(0.8).formatHex()) .attr("stroke-width", 1.2) .attr("filter", "url(#hdbar05-soft-shadow)"); svg.append("text") .attr("class", "label value-label left") .attr("x", x + w + 12) .attr("y", cy + 8) .attr("text-anchor", "start") .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", labelFontSize) .attr("font-weight", 700) .attr("fill", darkGreen) .text(labelText); } if (rightData) { const v = Math.max(0, +rightData[valueField] || 0); const w = Math.max(2, rightScale(v)); const x = rightAxisStart; const labelText = formatValue(v); const labelFontSize = Math.max(15, Math.min(29, rowBand * 0.42)); svg.append("path") .attr("class", "bar right-bar") .attr("data-dimension", formattedDimension) .attr("data-group", rightGroupText) .attr("data-value", v) .attr("d", barPath(x, y, w, barHeight)) .attr("fill", "url(#hdbar05-right-gradient)") .attr("stroke", d3.color(rightColor).darker(0.7).formatHex()) .attr("stroke-width", 1.2) .attr("filter", "url(#hdbar05-soft-shadow)"); svg.append("text") .attr("class", "label value-label right") .attr("x", x - 14) .attr("y", cy + 8) .attr("text-anchor", "end") .attr("font-family", "Georgia, Times New Roman, serif") .attr("font-size", labelFontSize) .attr("font-weight", 700) .attr("fill", rightColor) .text(labelText); } });
const slotY = height * 0.775; ["left", "right"].forEach((side) => { const x = side === "left" ? width * 0.08 : width * 0.75; const w = width * 0.18; const slot = svg.append("g") .attr("class", `reserved-asset-slot hdbar05-architecture-slot ${side}`) .attr("data-asset-slot", `${side}-architecture-background`) .attr("data-slot-policy", "image2_asset_or_retrieval_asset") .attr("data-asset-source-policy", "image2_asset_or_retrieval_asset") .attr("data-anchor", `${side}-lower-chart-background`) .attr("data-collision-rule", "remain behind chart-owned content; hide before overlapping data text or row slots") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-bbox", `${x.toFixed(1)},${slotY.toFixed(1)},${w.toFixed(1)},${(height * 0.115).toFixed(1)}`) .attr("opacity", 0); slot.append("rect").attr("x", x).attr("y", slotY).attr("width", w).attr("height", height * 0.115).attr("rx", 8).attr("fill", "none").attr("stroke", "none"); });
svg.append("metadata").text(JSON.stringify({ variation: "horizontal_diverging_bar_chart_05", selected_reference_geometry: { temporal_order: temporalDimension ? "chronological ascending" : "input order", bar_endpoint: "chamfered/slanted outer value edge, flat inner baseline edge, non-stacked", bar_baseline_relationship: "left bars share common left baseline after row icon region and extend rightward by value; right bars share common left baseline after blue value labels", value_labels: "green values outside/adjacent to green bar value ends; blue values just before/adjacent to blue bar starts", row_cards: "pale rounded row-local containers spanning each bar row and aligned to row centerlines", row_icon_slots: "per-row circular semantic reserved slots on both sides with bbox/anchor/collision metadata", center_axis_labels: "dark-green rounded pills aligned to the center spine; temporal labels remain chronological and non-temporal labels are truncated inside the pill", measure_headers: "top left/right measure headers above bar columns; no bottom 0-100 axes because selected reference does not show them", bottom_wrappers: "ignored", copied_assets: "none; asset-like regions are reserved slots only" } }));
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Diverging Bar Chart", "chart_name": "horizontal_diverging_bar_chart_06", "chart_for": "comparison", "is_composite": false, "required_fields": ["x", "y", "group", "group2"], "hierarchy":["group2"], "required_fields_type": [["categorical"], ["numerical"], ["categorical"], ["categorical"]], "required_fields_range": [[2, 20], [0, 10000], [1, 5], [1, 3]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["group"], "required_other_colors": [], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "no", "icon_mark": "none", "icon_label": "replace", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
// 全面优化的Split Comparison Chart实现function makeChart(containerSelector, data) { // ---------- 1. 数据准备阶段 ---------- // 提取数据和配置 const jsonData = data; const chartData = jsonData.data.data const variables = jsonData.variables || {}; const typography = jsonData.typography || { title: { font_family: "Arial", font_size: "24px", font_weight: "bold" }, label: { font_family: "Arial", font_size: "16px", font_weight: "normal" }, description: { font_family: "Arial", font_size: "14px", font_weight: "normal" }, annotation: { font_family: "Arial", font_size: "12px", font_weight: "normal" } }; const colors = jsonData.colors || { text_color: "#333333" }; const colorResolver = chartUtils.color.resolver(jsonData); const images = jsonData.images || { field: {}, other: {} }; const dataColumns = chartUtils.schema.columns(jsonData); // 设置默认视觉效果变量 variables.has_rounded_corners = variables.has_rounded_corners !== undefined ? variables.has_rounded_corners : true; variables.has_shadow = variables.has_shadow !== undefined ? variables.has_shadow : false; variables.has_gradient = variables.has_gradient !== undefined ? variables.has_gradient : false; variables.has_stroke = variables.has_stroke !== undefined ? variables.has_stroke : false; variables.has_spacing = variables.has_spacing !== undefined ? variables.has_spacing : true; // 数值格式化函数 // 清空容器 d3.select(containerSelector).html(""); // ---------- 2. 尺寸和布局设置 ---------- // 设置图表尺寸 const width = variables.width || 900; // 动态调整高度以适应所有数据 const rowHeight = 50; // 减小行高以容纳更多数据 const initialMargin = { top: 60, right: 40, bottom: 40, left: 40 }; // 提取字段名称 const xField = chartUtils.schema.channel(jsonData, "x").key; const yField = chartUtils.schema.channel(jsonData, "y").key; // 使用第一个 group 作为 categoryField,如果不存在则使用默认值 const categoryField = chartUtils.schema.channel(jsonData, "group").key; // 使用第二个 group 作为 developmentStatusField,如果不存在则使用默认值 const developmentStatusField = chartUtils.schema.channel(jsonData, "group2").key; // 获取唯一维度和类别 const allDimensions = [...new Set(chartData.map(d => d[xField]))]; const allLeaveTypes = [...new Set(chartData.map(d => d[categoryField]))]; const allDevelopmentStatuses = [...new Set(chartData.map(d => d[developmentStatusField]))]; // 确定左右两组的类别 let leftCategory, rightCategory; if (allLeaveTypes.length >= 2) { // 如果没有预期的值,但有至少两个类别,使用前两个 leftCategory = allLeaveTypes[0]; rightCategory = allLeaveTypes[1]; } else { // 默认值 leftCategory = "Left Category"; rightCategory = "Right Category"; } // 创建左右两侧数据 const leftData = {}; const rightData = {}; // 处理数据 chartData.forEach(item => { const dimension = item[xField]; const value = item[yField]; const category = item[categoryField]; const developmentStatus = item[developmentStatusField]; // 获取发展状态 // 左侧组数据 if (category === leftCategory) { leftData[dimension] = { dimension: dimension, value: value, developmentStatus: developmentStatus // 保存发展状态 }; } // 右侧组数据 if (category === rightCategory) { rightData[dimension] = { dimension: dimension, value: value, developmentStatus: developmentStatus // 保存发展状态 }; } }); // 对左右两组数据独立排序(按值从大到小) const sortedLeftData = Object.values(leftData) .sort((a, b) => b.value - a.value); const sortedRightData = Object.values(rightData) .sort((a, b) => b.value - a.value); // 确定行数(左右两侧中较长的一个) const rowCount = Math.max(sortedLeftData.length, sortedRightData.length); // 动态计算整体高度 const height = initialMargin.top + (rowCount * rowHeight) + initialMargin.bottom; // 计算实际图表区域尺寸 const margin = initialMargin; const innerWidth = width - margin.left - margin.right; const innerHeight = rowCount * rowHeight; // 设置布局参数 const centerX = innerWidth / 2; const rankCircleRadius = 18; // 缩小排名圆圈 const itemIconWidth = 40; // 缩小图标宽度 const itemIconHeight = 43; // 缩小图标高度 // ---------- 3. 创建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"); // 处理背景设置 if (jsonData.variation?.background === "styled") { svg.append("rect") .attr("width", width) .attr("height", height) .attr("fill", "#f9f9f9"); } else { // 添加原有的背景 - 使用棋盘格图案 svg.append("rect") .attr("width", width) .attr("height", height) .attr("fill", "url(#checkerboard)"); } // ---------- 4. 文本测量辅助函数 ---------- // 计算文本宽度的函数 const calculateTextWidth = (text, fontSize, fontWeight, fontFamily) => { return chartUtils.text.measure(svg, text, { fontFamily: fontFamily || typography.label.font_family, fontSize: fontSize || typography.label.font_size, fontWeight: fontWeight || typography.label.font_weight }).width; }; // ---------- 5. 创建视觉效果 ---------- const defs = svg.append("defs"); // 创建颜色获取函数 - 修改为同时考虑类别和发展状态 const getColor = (category, developmentStatus, index) => { // 基础颜色 - 左侧为绿色,右侧为蓝色 let baseColor; const fallbackColor = colorResolver.available(index, { cycle: true, fallback: category === leftCategory ? "#4BB462" : "#5271C7" }).value; baseColor = colorResolver.field(category, index, { fallback: fallbackColor }).value; // 根据发展状态调整颜色深浅 if (developmentStatus === allDevelopmentStatuses[0]) { // 深色版本 - 对于已发展国家 return baseColor; } else { // 浅色版本 - 对于发展中国家 // 将颜色转换为RGB,然后调亮 const rgb = d3.rgb(baseColor); return d3.rgb( Math.min(255, rgb.r + 60), Math.min(255, rgb.g + 60), Math.min(255, rgb.b + 60) ).toString(); } }; // 获取描边颜色 const getStrokeColor = () => { const stroke = colorResolver.other("stroke_color", { fallback: "" }).value; if (stroke) return stroke; return colorResolver.available(0, { fallback: "#333333" }).value; }; const strokeColor = getStrokeColor(); // 创建阴影效果(如果启用) if (variables.has_shadow) { const filter = defs.append("filter") .attr("id", "shadow") .attr("filterUnits", "userSpaceOnUse") .attr("width", "200%") .attr("height", "200%"); filter.append("feGaussianBlur") .attr("in", "SourceAlpha") .attr("stdDeviation", 2); filter.append("feOffset") .attr("dx", 2) .attr("dy", 2) .attr("result", "offsetblur"); const feMerge = filter.append("feMerge"); feMerge.append("feMergeNode"); feMerge.append("feMergeNode").attr("in", "SourceGraphic"); } // 创建渐变效果(如果启用) if (variables.has_gradient) { // 左侧渐变 const leftGradientId = `gradient-${leftCategory.replace(/\s+/g, '-').toLowerCase()}`; const leftBaseColor = getColor(leftCategory, allDevelopmentStatuses[0], 0); const leftGradient = defs.append("linearGradient") .attr("id", leftGradientId) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); leftGradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(leftBaseColor, { mode: "brighter", amount: 1.2 })); leftGradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(leftBaseColor, { mode: "darker", amount: 0.7 })); // 右侧渐变 const rightGradientId = `gradient-${rightCategory.replace(/\s+/g, '-').toLowerCase()}`; const rightBaseColor = getColor(rightCategory, allDevelopmentStatuses[0], 0); const rightGradient = defs.append("linearGradient") .attr("id", rightGradientId) .attr("x1", "100%") .attr("y1", "0%") .attr("x2", "0%") .attr("y2", "0%"); rightGradient.append("stop") .attr("offset", "0%") .attr("stop-color", colorResolver.variant(rightBaseColor, { mode: "brighter", amount: 1.2 })); rightGradient.append("stop") .attr("offset", "100%") .attr("stop-color", colorResolver.variant(rightBaseColor, { mode: "darker", amount: 0.7 })); } // ---------- 6. 计算状态标签宽度 ---------- // 计算所有可能的发展状态标签宽度 const statusLabelWidths = {}; allDevelopmentStatuses.forEach(status => { // 使用小字体(12px)计算状态标签的宽度 statusLabelWidths[status] = calculateTextWidth(status.toUpperCase(), "12px", "normal"); }); // 获取最大标签宽度,加上一些间距作为安全边距 const maxStatusLabelWidth = Math.max(...Object.values(statusLabelWidths)); // ---------- 7. 创建主图表组 ---------- const g = svg.append("g") .attr("transform", `translate(${margin.left},${margin.top})`); // 添加左右两侧的标题 let leftCategoryName = leftCategory; let rightCategoryName = rightCategory;
// 左右圆圈的起始X位置 const leftRankX = 0; const rightRankX = centerX + maxStatusLabelWidth - 20;
// 计算标题文本的宽度 let fontSize = typography.label.font_size; let fontSizeValue = parseFloat(fontSize); let leftTextWidth = calculateTextWidth(leftCategoryName, fontSize); let rightTextWidth = calculateTextWidth(rightCategoryName, fontSize);
// 计算每侧可用的最大宽度 const leftMaxWidth = centerX - 20; const rightMaxWidth = centerX - 20;
// 根据需要缩小字体,直到文本适合最大宽度 // 同时确保左右标题使用相同的字体大小 const minFontSize = 10; while ((leftTextWidth > leftMaxWidth || rightTextWidth > rightMaxWidth) && fontSizeValue > minFontSize) { // 减小字体大小 fontSizeValue -= 1; fontSize = fontSizeValue + "px"; leftTextWidth = calculateTextWidth(leftCategoryName, fontSize); rightTextWidth = calculateTextWidth(rightCategoryName, fontSize); }
// 计算标题矩形的宽度,确保适合文本 const leftRectWidth = leftTextWidth + 10; // 在文本两侧添加一些填充 const rightRectWidth = rightTextWidth + 10;
// 左侧标题 - 与左侧圆圈对齐 const leftTitleGroup = g.append("g") .attr("transform", `translate(${leftRankX}, -20)`);
leftTitleGroup.append("rect") .attr("x", 0) .attr("y", -15) .attr("width", leftRectWidth) .attr("height", 25) .attr("fill", "#000");
leftTitleGroup.append("text") .attr("x", leftRectWidth / 2) .attr("y", 0) .attr("text-anchor", "middle") .attr("dy", "0.35em") .style("font-family", typography.label.font_family) .style("font-size", fontSize) .style("font-weight", typography.label.font_weight) .style("fill", "#fff") .text(leftCategoryName);
// 右侧标题 - 与右侧圆圈对齐 const rightTitleGroup = g.append("g") .attr("transform", `translate(${rightRankX}, -20)`);
rightTitleGroup.append("rect") .attr("x", 0) .attr("y", -15) .attr("width", rightRectWidth) .attr("height", 25) .attr("fill", "#000");
rightTitleGroup.append("text") .attr("x", rightRectWidth / 2) .attr("y", 0) .attr("text-anchor", "middle") .attr("dy", "0.35em") .style("font-family", typography.label.font_family) .style("font-size", fontSize) .style("font-weight", typography.label.font_weight) .style("fill", "#fff") .text(rightCategoryName); // ---------- 8. 创建数据可视化 ---------- // 添加交替行背景 if (jsonData.variation?.background === "styled") { sortedLeftData.forEach((item, i) => { if (i % 2 === 0) { g.append("rect") .attr("x", -margin.left/2) .attr("y", i * rowHeight) .attr("width", innerWidth + margin.left/2 + margin.right/2) .attr("height", rowHeight) .attr("class", "background") .attr("fill", "#f5f5f5") .attr("opacity", 0.8); } }); } // 找出所有数据中的最大值,确保左右两侧使用统一比例尺 const allValues = [...sortedLeftData.map(d => d.value), ...sortedRightData.map(d => d.value)]; const globalMaxValue = Math.max(...allValues);
// 左侧排名圆圈和图标所占空间 const leftIconSpace = rankCircleRadius * 3 + itemIconWidth + 10; // 右侧排名圆圈和图标所占空间 const rightIconSpace = rankCircleRadius * 3 + itemIconWidth + 10; // 左侧安全边距 const leftSafetyMargin = 10; // 右侧安全边距 (包括状态标签的宽度) const rightSafetyMargin = maxStatusLabelWidth + 15;
// 计算左右两侧可用的最大宽度 const leftMaxBarWidth = centerX - leftIconSpace - leftSafetyMargin; const rightMaxBarWidth = centerX - rightIconSpace - leftSafetyMargin;
// 创建统一的柱状图比例尺 - 左侧 const leftBarScale = d3.scaleLinear() .domain([0, globalMaxValue]) .range([0, leftMaxBarWidth]);
// 创建统一的柱状图比例尺 - 右侧 // 使用相同的比例关系,确保左右两侧相同值的柱子长度相同 const rightBarScale = d3.scaleLinear() .domain([0, globalMaxValue]) .range([0, rightMaxBarWidth]); // 用于跟踪左侧已经显示过的发展状态 const leftShownStatusLabels = new Set(); // 绘制左侧条目 sortedLeftData.forEach((item, index) => { const dimension = item.dimension; const value = item.value; const developmentStatus = item.developmentStatus; const yPos = index * rowHeight; // 此行的起始y位置 // 8.1 绘制排名圆圈和数字 const rankX = 20; const rankY = yPos + rowHeight / 2; const rankGroup = g.append("g") .attr("transform", `translate(${rankX}, ${rankY})`); rankGroup.append("circle") .attr("r", rankCircleRadius) .attr("fill", "#000"); rankGroup.append("text") .attr("text-anchor", "middle") .attr("dy", "0.35em") .style("font-family", typography.label.font_family) .style("font-size", typography.label.font_size) .style("font-weight",typography.label.font_weight) .style("fill", "#fff") .text(index + 1); // 8.2 添加维度图标(如国家标志)- 紧接圆圈右边 const iconX = rankX + rankCircleRadius + 3; const iconY = rankY - itemIconHeight / 2; // 如果有图标则使用 if (images.field && images.field[dimension]) { g.append("image") .attr("x", iconX) .attr("y", iconY) .attr("width", itemIconWidth) .attr("height", itemIconHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // 8.3 显示左侧值(柱状图) const barStartX = iconX + itemIconWidth + 5; const barWidth = leftBarScale(value); // 根据值计算长度 const barHeight = rowHeight * 0.85; const barY = yPos + (rowHeight - barHeight) / 2; const boxColor = getColor(leftCategory, developmentStatus, index); const FontSize = Math.floor(barHeight * 0.5) + "px"; // 确定填充颜色,考虑渐变效果 const fillColor = variables.has_gradient ? `url(#gradient-${leftCategory.replace(/\s+/g, '-').toLowerCase()})` : boxColor; // 绘制值框 - 使用原始矩形形状 g.append("rect") .attr("x", barStartX) .attr("y", barY) .attr("width", barWidth) .attr("height", barHeight) .attr("rx", variables.has_rounded_corners ? 5 : 0) .attr("ry", variables.has_rounded_corners ? 5 : 0) .attr("fill", fillColor) .style("stroke", variables.has_stroke ? strokeColor : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); }); // For the left bar values: // First, calculate the text width const leftFormattedValue = `${chartUtils.format.autoText(value)}${valueUnit}`;
// Get text width const leftTextWidth = chartUtils.text.measure(g, leftFormattedValue, { fontFamily: typography.label.font_family, fontSize: FontSize, fontWeight: typography.label.font_weight }).width;
// Define minimum width needed for text to fit comfortably const leftMinWidthForText = leftTextWidth + 10; // Add padding
// Check if bar is wide enough for text if (barWidth < leftMinWidthForText) { // Bar too narrow - place text outside left edge g.append("text") .attr("x", barStartX + barWidth + 16) // Position right of the bar .attr("y", barY + barHeight / 2) .attr("text-anchor", "end") // Right align .attr("dy", "0.35em") .style("font-family", typography.label.font_family) .style("font-size", FontSize) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) // Use default text color .text(leftFormattedValue); } else { // Bar wide enough - place text inside g.append("text") .attr("x", barStartX + barWidth - leftTextWidth) .attr("y", barY + barHeight / 2) .attr("text-anchor", "middle") .attr("dy", "0.35em") .style("font-family", typography.label.font_family) .style("font-size", FontSize) .style("font-weight", typography.label.font_weight) .style("fill", "#fff") // White text for inside bar .text(leftFormattedValue); } // 如果此发展状态尚未显示过标签,则添加 if (!leftShownStatusLabels.has(developmentStatus)) { leftShownStatusLabels.add(developmentStatus); g.append("text") .attr("x", barStartX + barWidth + 5) .attr("y", barY + barHeight / 2) .attr("text-anchor", "start") .attr("dy", "0.35em") .style("font-family", typography.label.font_family) .style("font-size", "12px") .style("font-weight",typography.label.font_weight) .style("fill", boxColor) .text(developmentStatus.toUpperCase()); } }); // 用于跟踪右侧已经显示过的发展状态 const rightShownStatusLabels = new Set(); // 绘制右侧条目 sortedRightData.forEach((item, index) => { const dimension = item.dimension; const value = item.value; const developmentStatus = item.developmentStatus; const yPos = index * rowHeight; // 此行的起始y位置 // 8.1 绘制排名圆圈和数字 const rankX = centerX + maxStatusLabelWidth - 25; const rankY = yPos + rowHeight / 2; // 8.2 添加维度图标(如国家标志)- 紧接圆圈右边 const iconX = rankX + 3; const iconY = rankY - itemIconHeight / 2; // 如果有图标则使用 if (images.field && images.field[dimension]) { g.append("image") .attr("x", iconX) .attr("y", iconY) .attr("width", itemIconWidth) .attr("height", itemIconHeight) .attr("preserveAspectRatio","xMidYMid meet") .attr("xlink:href", images.field[dimension]); } // 8.3 显示右侧值(柱状图) const barStartX = iconX + itemIconWidth + 5; const barWidth = rightBarScale(value); // 根据值计算长度 const barHeight = rowHeight * 0.85; const barY = yPos + (rowHeight - barHeight) / 2; const boxColor = getColor(rightCategory, developmentStatus, index); const FontSize = Math.floor(barHeight * 0.5) + "px"; // 确定填充颜色,考虑渐变效果 const fillColor = variables.has_gradient ? `url(#gradient-${rightCategory.replace(/\s+/g, '-').toLowerCase()})` : boxColor; // 绘制值框 - 使用原始矩形形状 g.append("rect") .attr("x", barStartX) .attr("y", barY) .attr("width", barWidth) .attr("height", barHeight) .attr("rx", variables.has_rounded_corners ? 5 : 0) .attr("ry", variables.has_rounded_corners ? 5 : 0) .attr("fill", fillColor) .style("stroke", variables.has_stroke ? strokeColor : "none") .style("stroke-width", variables.has_stroke ? 1 : 0) .style("filter", variables.has_shadow ? "url(#shadow)" : "none") .on("mouseover", function() { d3.select(this).attr("opacity", 0.8); }) .on("mouseout", function() { d3.select(this).attr("opacity", 1); }); // For the right bar values: // First, calculate the text width const rightFormattedValue = `${chartUtils.format.autoText(value)}${valueUnit}`;
// Get text width const rightTextWidth = chartUtils.text.measure(g, rightFormattedValue, { fontFamily: typography.label.font_family, fontSize: FontSize, fontWeight: typography.label.font_weight }).width;
// Define minimum width needed for text to fit comfortably const rightMinWidthForText = rightTextWidth + 10; // Add padding
// Check if bar is wide enough for text if (barWidth < rightMinWidthForText) { // Bar too narrow - place text outside right edge g.append("text") .attr("x", barStartX + barWidth + 5) // Position right of the bar .attr("y", barY + barHeight / 2) .attr("text-anchor", "start") // Left align .attr("dy", "0.35em") .style("font-family", typography.label.font_family) .style("font-size", FontSize) .style("font-weight", typography.label.font_weight) .style("fill", colorResolver.text({ fallback: "#333333" }).value) // Use default text color .text(rightFormattedValue); } else { // Bar wide enough - place text inside g.append("text") .attr("x", barStartX + barWidth - rightTextWidth ) .attr("y", barY + barHeight / 2) .attr("text-anchor", "middle") .attr("dy", "0.35em") .style("font-family", typography.label.font_family) .style("font-size", FontSize) .style("font-weight", typography.label.font_weight) .style("fill", "#fff") // White text for inside bar .text(rightFormattedValue); } // 如果此发展状态尚未显示过标签,则添加 if (!rightShownStatusLabels.has(developmentStatus)) { rightShownStatusLabels.add(developmentStatus); // 将标签固定在预留的空间内,避免与柱状图重叠 g.append("text") .attr("x", barStartX + barWidth + 5) .attr("y", barY + barHeight / 2) .attr("text-anchor", "start") .attr("dy", "0.35em") .style("font-family", typography.label.font_family) .style("font-size", "12px") .style("font-weight",typography.label.font_weight) .style("fill", boxColor) .text(developmentStatus.toUpperCase()); } }); // 返回SVG节点 return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Diverging Bar Chart", "chart_name": "horizontal_diverging_bar_chart_07", "chart_for": "comparison", "is_composite": false, "required_fields": ["x", "y", "group"], "required_fields_type": [["categorical", "temporal"], ["numerical"], ["categorical"]], "required_fields_range": [[2, 20], [0, "inf"], [2, 2]], "required_fields_icons": [], "required_other_icons": [], "required_fields_colors": ["group"], "required_other_colors": [], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "styled", "icon_mark": "none", "icon_label": "none", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const jsonData = data; const rows = (jsonData.data && jsonData.data.data) || []; const variables = jsonData.variables || {}; const width = +variables.width || 1024; const height = +variables.height || 1536; const columns = chartUtils.schema.columns(jsonData); const dimensionChannel = chartUtils.schema.channel(jsonData, "x"); const valueChannel = chartUtils.schema.channel(jsonData, "y"); const groupChannel = chartUtils.schema.channel(jsonData, "group"); const dimensionField = dimensionChannel.key; const valueField = valueChannel.key; const groupField = groupChannel.key; const valueUnit = valueChannel.unit && valueChannel.unit !== "none" ? valueChannel.unit : ""; const dimensionUnit = dimensionChannel.unit && dimensionChannel.unit !== "none" ? dimensionChannel.unit : ""; const colorResolver = chartUtils.color.resolver(jsonData);
d3.select(containerSelector).html("");
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("data-chart-variation", "horizontal_diverging_bar_chart_07") .attr("data-reference-policy", "code-generated-layout-no-embedded-raster");
const defs = svg.append("defs"); defs.append("filter") .attr("id", "hdbar07-card-shadow") .attr("x", "-12%") .attr("y", "-8%") .attr("width", "124%") .attr("height", "116%") .html(` <feDropShadow dx="0" dy="18" stdDeviation="18" flood-color="#4777A7" flood-opacity="0.18"/> <feDropShadow dx="0" dy="2" stdDeviation="2" flood-color="#0E2E5A" flood-opacity="0.10"/> `);
const pageGradient = defs.append("linearGradient") .attr("id", "hdbar07-page-bg") .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "100%"); pageGradient.append("stop").attr("offset", "0%").attr("stop-color", "#F4FBFF"); pageGradient.append("stop").attr("offset", "100%").attr("stop-color", "#DCEEFF");
function makeLinearGradient(id, c0, c1) { const grad = defs.append("linearGradient") .attr("id", id) .attr("x1", "0%") .attr("y1", "0%") .attr("x2", "100%") .attr("y2", "0%"); grad.append("stop").attr("offset", "0%").attr("stop-color", c0); grad.append("stop").attr("offset", "100%").attr("stop-color", c1); } makeLinearGradient("hdbar07-green-bar", "#7DD957", "#44A83D"); makeLinearGradient("hdbar07-blue-bar", "#367BF4", "#1257D8"); makeLinearGradient("hdbar07-row", "#FFFFFF", "#F8FCFF"); makeLinearGradient("hdbar07-metric", "#F8FCFF", "#FFFFFF");
const columnByName = new Map(columns.map(col => [col.name, col])); const isTemporalDimension = /temporal|date|time/i.test(String((columnByName.get(dimensionField) || {}).data_type || "")); const monthRank = { 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 };
function temporalRank(value) { const s = String(value).trim(); const numeric = Number(s); if (/^\d{4}$/.test(s)) return numeric; const date = Date.parse(s); if (!Number.isNaN(date)) return date; const lower = s.toLowerCase(); if (monthRank[lower]) return monthRank[lower]; const yearMatch = lower.match(/\b(19|20)\d{2}\b/); if (yearMatch) return Number(yearMatch[0]); return s; }
const groups = Array.from(new Set(rows.map(d => d[groupField]))).slice(0, 2); const leftGroup = groups[0] || "Group A"; const rightGroup = groups[1] || "Group B"; const dimensions = Array.from(new Set(rows.map(d => d[dimensionField]))).sort((a, b) => { if (!isTemporalDimension && !/year|month|date|season|quarter/i.test(dimensionField)) { return rows.findIndex(d => d[dimensionField] === a) - rows.findIndex(d => d[dimensionField] === b); } const ar = temporalRank(a); const br = temporalRank(b); if (typeof ar === "number" && typeof br === "number") return ar - br; return String(ar).localeCompare(String(br), undefined, { numeric: true }); }); const dimensionLabels = new Map(dimensions.map(dimension => [ dimension, dimensionUnit ? `${dimension}${dimensionUnit}` : `${dimension}` ])); const maxDimensionLabelChars = d3.max(Array.from(dimensionLabels.values()).map(label => String(label).length)) || 0;
const byDimGroup = new Map(); rows.forEach(d => { byDimGroup.set(`${d[dimensionField]}|||${d[groupField]}`, d); });
function valueFor(dimension, group) { const row = byDimGroup.get(`${dimension}|||${group}`); return row ? Math.max(0, +row[valueField] || 0) : 0; }
const values = rows.map(d => Math.max(0, +d[valueField] || 0)); const maxValue = Math.max(1, d3.max(values) || 1); const maxLeftValue = Math.max(1, d3.max(rows.filter(d => d[groupField] === leftGroup), d => Math.max(0, +d[valueField] || 0)) || 1); const maxRightValue = Math.max(1, d3.max(rows.filter(d => d[groupField] === rightGroup), d => Math.max(0, +d[valueField] || 0)) || 1);
function displayValue(value) { const formatted = chartUtils.format.autoText(value); return valueUnit ? `${formatted}${valueUnit}` : formatted; }
function fittedFontSize(text, maxWidth, baseSize, minSize, factor = 0.58) { const length = Math.max(1, String(text || "").length); return Math.max(minSize, Math.min(baseSize, maxWidth / (length * factor))); }
function measuredTextWidth(text, fontSize, fontWeight, fontFamily) { const label = String(text || ""); const probe = svg.append("text") .attr("x", -9999) .attr("y", -9999) .attr("font-family", fontFamily || "Arial, sans-serif") .attr("font-size", fontSize) .attr("font-weight", fontWeight || 400) .attr("visibility", "hidden") .text(label); let widthEstimate; try { widthEstimate = probe.node().getComputedTextLength(); } catch (e) { widthEstimate = label.length * fontSize * 0.62; } probe.remove(); return Number.isFinite(widthEstimate) && widthEstimate > 0 ? widthEstimate : label.length * fontSize * 0.62; }
function truncateToWidth(text, maxWidth, fontSize, fontWeight, fontFamily) { const label = String(text || ""); if (measuredTextWidth(label, fontSize, fontWeight, fontFamily) <= maxWidth) return label; let lo = 0; let hi = label.length; while (lo < hi) { const mid = Math.ceil((lo + hi) / 2); const candidate = `${label.slice(0, mid).trimEnd()}...`; if (measuredTextWidth(candidate, fontSize, fontWeight, fontFamily) <= maxWidth) { lo = mid; } else { hi = mid - 1; } } return `${label.slice(0, Math.max(1, lo)).trimEnd()}...`; }
function wrapWordsToWidth(text, maxWidth, fontSize, fontWeight, fontFamily, maxLines) { const words = String(text || "").trim().split(/\s+/).filter(Boolean); if (!words.length) return [""]; const lines = []; let line = ""; words.forEach(word => { const candidate = line ? `${line} ${word}` : word; if (!line || measuredTextWidth(candidate, fontSize, fontWeight, fontFamily) <= maxWidth) { line = candidate; } else { lines.push(line); line = word; } }); if (line) lines.push(line); return lines; }
function wrapWordsToWidthWithFallback(text, maxWidth, fontSize, fontWeight, fontFamily, maxLines) { const lines = wrapWordsToWidth(text, maxWidth, fontSize, fontWeight, fontFamily, maxLines); if (lines.length <= maxLines) { return lines.map(ln => truncateToWidth(ln, maxWidth, fontSize, fontWeight, fontFamily)); } const kept = lines.slice(0, maxLines - 1); const tail = lines.slice(maxLines - 1).join(" "); kept.push(truncateToWidth(tail, maxWidth, fontSize, fontWeight, fontFamily)); return kept; }
function headerLabelLayout(text, maxWidth) { const fontFamily = "Arial, sans-serif"; const fontWeight = 900; for (let size = 35; size >= 20; size -= 1) { const singleLineWidth = measuredTextWidth(text, size, fontWeight, fontFamily); if (singleLineWidth <= maxWidth) { return { lines: [String(text || "")], size, lineHeight: size * 0.96, family: fontFamily }; } const lines = wrapWordsToWidth(text, maxWidth, size, fontWeight, fontFamily, 2); const maxLineWidth = d3.max(lines.map(line => measuredTextWidth(line, size, fontWeight, fontFamily))) || 0; if (lines.length <= 2 && maxLineWidth <= maxWidth) { return { lines, size, lineHeight: size * 0.96, family: fontFamily }; } } const size = 20; return { lines: wrapWordsToWidthWithFallback(text, maxWidth, size, fontWeight, fontFamily, 2), size, lineHeight: size * 0.96, family: fontFamily }; }
function maxValueLabelChars(group) { return d3.max(dimensions.map(dimension => displayValue(valueFor(dimension, group)).length)) || 0; }
function groupColor(group, side) { const resolved = colorResolver.field(group, 0, { fallbackKey: side === "left" ? "positive" : "primary" }).value; if (/android|sustainable|natural|green/i.test(String(group))) return "#2D8F2F"; if (/ios|nfl|blue|digital/i.test(String(group))) return "#1358D6"; return resolved || (side === "left" ? "#2D8F2F" : "#1358D6"); }
const leftColor = groupColor(leftGroup, "left"); const rightColor = groupColor(rightGroup, "right"); const navy = "#10284F"; const blue = "#175FE8"; const muted = "#556174";
svg.append("rect") .attr("width", width) .attr("height", height) .attr("fill", "url(#hdbar07-page-bg)");
const card = { x: width * 0.028, y: height * 0.022, w: width * 0.944, h: height * 0.953 };
svg.append("rect") .attr("x", card.x) .attr("y", card.y) .attr("width", card.w) .attr("height", card.h) .attr("rx", 18) .attr("fill", "#FFFFFF") .attr("stroke", "#C8DDF3") .attr("stroke-width", 1.2) .attr("filter", "url(#hdbar07-card-shadow)");
svg.append("rect") .attr("x", card.x + 18) .attr("y", card.y + 24) .attr("width", card.w - 36) .attr("height", card.h - 48) .attr("rx", 14) .attr("fill", "#F9FDFF") .attr("opacity", 0.32);
function appendSlot(parent, cfg) { const g = parent.append("g") .attr("class", `reserved-asset-slot ${cfg.className || ""}`) .attr("data-asset-slot", cfg.slot) .attr("data-slot-policy", "neutral_placeholder_or_image2_asset") .attr("data-asset-source-policy", "neutral_placeholder_or_image2_asset") .attr("data-anchor", cfg.anchor) .attr("data-collision-rule", cfg.collision) .attr("data-bbox", `${cfg.x.toFixed(2)},${cfg.y.toFixed(2)},${cfg.size.toFixed(2)},${cfg.size.toFixed(2)}`) .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("transform", `translate(${cfg.x},${cfg.y})`); g.append("circle") .attr("cx", cfg.size / 2) .attr("cy", cfg.size / 2) .attr("r", cfg.size / 2 - 2) .attr("fill", cfg.fill || "#EEF6FF") .attr("stroke", cfg.stroke || "#B8D0EF") .attr("stroke-width", 2) .attr("stroke-dasharray", cfg.dash || "none"); if (cfg.label) { g.append("text") .attr("x", cfg.size / 2) .attr("y", cfg.size / 2 + cfg.size * 0.13) .attr("text-anchor", "middle") .attr("font-family", "Arial, sans-serif") .attr("font-size", cfg.size * 0.34) .attr("font-weight", 800) .attr("fill", cfg.textColor || muted) .text(cfg.label); } return g; }
appendSlot(svg, { slot: "title-art-icon", className: "title-art-icon-slot", x: width / 2 - 41, y: 8, size: 82, fill: "#FFFFFF", stroke: "#C8DDF3", dash: "7 6", anchor: "top-center-card-edge", collision: "overlap-card-edge-only;avoid-title-text", label: "" });
function splitTitle(title) { const words = String(title || "").trim().split(/\s+/).filter(Boolean); if (words.length <= 4) return [words.join(" "), ""]; const preferred = words.findIndex(w => /^(in|by|from|than|vs\\.?|versus)$/i.test(w)); const cut = preferred > 1 && preferred < words.length - 1 ? preferred : Math.ceil(words.length / 2); return [words.slice(0, cut).join(" "), words.slice(cut).join(" ")]; }
function addWrappedText(parent, text, x, y, maxChars, lineHeight, attrs) { const words = String(text || "").trim().split(/\s+/).filter(Boolean); const lines = []; let line = ""; words.forEach(word => { const candidate = line ? `${line} ${word}` : word; if (candidate.length <= maxChars || !line) { line = candidate; } else { lines.push(line); line = word; } }); if (line) lines.push(line); const t = parent.append("text") .attr("x", x) .attr("y", y) .attr("text-anchor", attrs.anchor || "middle") .attr("font-family", attrs.family || "Arial, sans-serif") .attr("font-size", attrs.size) .attr("font-weight", attrs.weight || 400) .attr("fill", attrs.fill || muted) .attr("letter-spacing", "0"); lines.slice(0, attrs.maxLines || 3).forEach((ln, i) => { t.append("tspan") .attr("x", x) .attr("dy", i === 0 ? 0 : lineHeight) .text(ln); }); return lines.length; }
const titleText = (jsonData.titles && jsonData.titles.main_title) || (jsonData.metadata && jsonData.metadata.title) || "Horizontal Diverging Bar Chart"; const subtitleText = (jsonData.titles && jsonData.titles.sub_title) || (jsonData.metadata && jsonData.metadata.description) || ""; const titleLines = splitTitle(titleText.toUpperCase()); const longestTitleLine = Math.max(titleLines[0].length, titleLines[1].length); const titleMaxWidth = card.w - 120; const titleSize = Math.min(width < 760 ? 42 : 58, Math.max(36, titleMaxWidth / Math.max(1, longestTitleLine * 0.60))); const titleTop = card.y + 102;
svg.append("text") .attr("x", width / 2) .attr("y", titleTop) .attr("text-anchor", "middle") .attr("font-family", "Arial Narrow, Arial, sans-serif") .attr("font-size", titleSize) .attr("font-weight", 900) .attr("fill", navy) .attr("letter-spacing", "0") .text(titleLines[0]); svg.append("text") .attr("x", width / 2) .attr("y", titleTop + titleSize * 1.18) .attr("text-anchor", "middle") .attr("font-family", "Arial Narrow, Arial, sans-serif") .attr("font-size", titleSize * 0.92) .attr("font-weight", 900) .attr("fill", blue) .attr("letter-spacing", "0") .text(titleLines[1] || "");
const dividerY = titleTop + titleSize * 1.82; svg.append("line") .attr("x1", width / 2 - 42) .attr("x2", width / 2 + 42) .attr("y1", dividerY) .attr("y2", dividerY) .attr("stroke", blue) .attr("stroke-width", 5) .attr("stroke-linecap", "round");
addWrappedText(svg, subtitleText, width / 2, dividerY + 42, 46, 34, { size: 27, fill: "#344051", family: "Arial, sans-serif", weight: 400, maxLines: 2 });
const headerY = card.y + 390; const plot = { x: card.x + 38, y: card.y + 500, w: card.w - 76, h: Math.min(card.h * 0.49, height - card.y - 660) }; const metricY = plot.y + plot.h + 34; const metricH = Math.max(108, Math.min(140, card.y + card.h - metricY - 84)); const rowGap = Math.max(13, Math.min(22, plot.h / Math.max(10, dimensions.length * 3.1))); const rowStep = plot.h / Math.max(1, dimensions.length); const rowH = Math.max(34, Math.min(94, rowStep - rowGap)); const barH = Math.max(18, Math.min(56, rowH * 0.48)); const centerX = width / 2; const baseRailW = Math.max(86, width * 0.095); const railW = maxDimensionLabelChars > 6 ? Math.max(baseRailW, Math.min(width * 0.22, Math.max(124, maxDimensionLabelChars * 10.2))) : baseRailW; const railLeft = centerX - railW / 2; const railRight = centerX + railW / 2; const leftValueX = plot.x + Math.max(62, width * 0.07); const rightValueX = plot.x + plot.w - Math.max(24, width * 0.025); const leftBarEnd = railLeft - 20; const rightBarStart = railRight + 26; const leftLabelChars = maxValueLabelChars(leftGroup); const rightLabelChars = maxValueLabelChars(rightGroup); const denseLeftValueGap = leftLabelChars > 5 ? Math.max(158, width * 0.158) : Math.max(92, width * 0.11); const denseRightValueGap = rightLabelChars > 5 ? Math.max(152, width * 0.148) : Math.max(96, width * 0.092); const leftBarStartMin = leftValueX + denseLeftValueGap; const rightBarMaxW = rightValueX - rightBarStart - denseRightValueGap; const leftBarMaxW = leftBarEnd - leftBarStartMin; const minBarW = Math.max(48, width * 0.06); const leftBarScale = d3.scaleLinear() .domain([0, maxLeftValue]) .range([minBarW, Math.max(minBarW, leftBarMaxW)]); const rightBarScale = d3.scaleLinear() .domain([0, maxRightValue]) .range([minBarW, Math.max(minBarW, rightBarMaxW)]); const valueFontSize = Math.max(22, Math.min(34, rowH * 0.39, (leftLabelChars > 5 || rightLabelChars > 5) ? 27 : 34)); const dimensionFontSize = Math.max(15, Math.min(27, rowH * 0.34, railW / Math.max(1, maxDimensionLabelChars * 0.58))); const barCornerRadius = Math.max(5, Math.min(9, barH * 0.18));
function addHeader(side, group, x, color, slot) { const iconSize = 94; appendSlot(svg, { slot, className: `${side}-group-icon-slot`, x, y: headerY, size: iconSize, fill: side === "left" ? "#E7F6DE" : "#E7F0FF", stroke: side === "left" ? "#D7EBCD" : "#D6E3FA", anchor: `${side}-group-header-leading-circle`, collision: "stay-above-plot-rows-and-inside-card", label: String(group).trim().slice(0, 1).toUpperCase(), textColor: color }); const tx = x + iconSize + 28; const groupLabel = String(group).toUpperCase(); const groupMaxWidth = side === "left" ? Math.max(90, railLeft - tx - 22) : Math.max(90, card.x + card.w - tx - 30); const groupLayout = headerLabelLayout(groupLabel, groupMaxWidth); const groupTitleY = headerY + (groupLayout.lines.length > 1 ? 38 : 48); const groupText = svg.append("text") .attr("x", tx) .attr("y", groupTitleY) .attr("font-family", groupLayout.family) .attr("font-size", groupLayout.size) .attr("font-weight", 900) .attr("fill", color) .attr("text-anchor", "start"); groupLayout.lines.forEach((line, index) => { groupText.append("tspan") .attr("x", tx) .attr("dy", index === 0 ? 0 : groupLayout.lineHeight) .text(line); }); const subtitleY = Math.min(headerY + 96, groupTitleY + (groupLayout.lines.length - 1) * groupLayout.lineHeight + 33); svg.append("text") .attr("x", tx) .attr("y", subtitleY) .attr("font-family", "Arial, sans-serif") .attr("font-size", 22) .attr("font-weight", 400) .attr("fill", "#344051") .attr("text-anchor", "start") .text(valueUnit ? `${valueField.replace(/([a-z])([A-Z])/g, "$1 $2")} (${valueUnit})` : valueField.replace(/([a-z])([A-Z])/g, "$1 $2")); }
addHeader("left", leftGroup, plot.x + 26, leftColor, "left-group-icon"); addHeader("right", rightGroup, rightBarStart + 12, rightColor, "right-group-icon");
svg.append("text") .attr("x", centerX) .attr("y", headerY + 88) .attr("text-anchor", "middle") .attr("font-family", "Arial, sans-serif") .attr("font-size", 22) .attr("font-weight", 800) .attr("fill", "#3A4658") .text(String(dimensionField).toUpperCase());
const railTop = plot.y + 12; const railBottom = plot.y + plot.h - 12;
dimensions.forEach((dimension, i) => { const rowY = plot.y + i * rowStep + (rowStep - rowH) / 2; const cy = rowY + rowH / 2; svg.append("rect") .attr("x", plot.x) .attr("y", rowY) .attr("width", plot.w) .attr("height", rowH) .attr("rx", Math.min(16, rowH * 0.22)) .attr("fill", "url(#hdbar07-row)") .attr("stroke", "#EDF4FC") .attr("stroke-width", 1);
const leftValue = valueFor(dimension, leftGroup); const rightValue = valueFor(dimension, rightGroup); const leftW = Math.min(leftBarMaxW, leftBarScale(leftValue)); const rightW = Math.min(rightBarMaxW, rightBarScale(rightValue)); const leftX = leftBarEnd - leftW; const rightX = rightBarStart;
svg.append("text") .attr("x", leftValueX) .attr("y", cy + 9) .attr("text-anchor", "start") .attr("font-family", "Arial Narrow, Arial, sans-serif") .attr("font-size", valueFontSize) .attr("font-weight", 800) .attr("fill", leftColor) .text(displayValue(leftValue));
svg.append("rect") .attr("class", "bar bar-left") .attr("data-dimension", String(dimension)) .attr("data-group", String(leftGroup)) .attr("data-value", leftValue) .attr("x", leftX) .attr("y", cy - barH / 2) .attr("width", Math.max(2, leftW)) .attr("height", barH) .attr("rx", barCornerRadius) .attr("ry", barCornerRadius) .attr("fill", "url(#hdbar07-green-bar)") .attr("stroke", "#3E9D35") .attr("stroke-width", 1);
svg.append("rect") .attr("x", leftX + 4) .attr("y", cy - barH / 2 + 3) .attr("width", Math.max(0, leftW - 10)) .attr("height", Math.max(2, barH * 0.26)) .attr("rx", barH * 0.13) .attr("fill", "#A4EA84") .attr("opacity", 0.24) .attr("pointer-events", "none");
svg.append("text") .attr("x", centerX) .attr("y", cy + 8) .attr("text-anchor", "middle") .attr("font-family", "Arial, sans-serif") .attr("font-size", dimensionFontSize) .attr("font-weight", 500) .attr("fill", "#3D4758") .text(dimensionLabels.get(dimension));
svg.append("rect") .attr("class", "bar bar-right") .attr("data-dimension", String(dimension)) .attr("data-group", String(rightGroup)) .attr("data-value", rightValue) .attr("x", rightX) .attr("y", cy - barH / 2) .attr("width", Math.max(2, rightW)) .attr("height", barH) .attr("rx", barCornerRadius) .attr("ry", barCornerRadius) .attr("fill", "url(#hdbar07-blue-bar)") .attr("stroke", "#145BD6") .attr("stroke-width", 1);
svg.append("rect") .attr("x", rightX + 4) .attr("y", cy - barH / 2 + 3) .attr("width", Math.max(0, rightW - 10)) .attr("height", Math.max(2, barH * 0.26)) .attr("rx", barH * 0.13) .attr("fill", "#6BA2FF") .attr("opacity", 0.24) .attr("pointer-events", "none");
svg.append("text") .attr("x", rightValueX) .attr("y", cy + 9) .attr("text-anchor", "end") .attr("font-family", "Arial Narrow, Arial, sans-serif") .attr("font-size", valueFontSize) .attr("font-weight", 800) .attr("fill", rightColor) .text(displayValue(rightValue)); });
[railLeft, railRight].forEach(x => { svg.append("line") .attr("x1", x) .attr("x2", x) .attr("y1", railTop) .attr("y2", railBottom) .attr("stroke", "#D3E2F3") .attr("stroke-width", 2) .attr("stroke-dasharray", "8 12") .attr("pointer-events", "none"); });
function growthFor(group) { const firstDim = dimensions[0]; const lastDim = dimensions[dimensions.length - 1]; const first = valueFor(firstDim, group); const last = valueFor(lastDim, group); if (!first) return null; return { firstDim, lastDim, pct: ((last - first) / first) * 100 }; }
const metricX = plot.x; const metricW = plot.w; const metric = svg.append("g") .attr("class", "chart-owned-growth-metric-strip") .attr("data-chart-owned-annotation", "growth-from-first-to-last-dimension") .attr("data-no-bottom-source-footer", "true") .attr("data-ignored-reference-footer", "source-line-omitted");
metric.append("rect") .attr("x", metricX) .attr("y", metricY) .attr("width", metricW) .attr("height", metricH) .attr("rx", 16) .attr("fill", "url(#hdbar07-metric)") .attr("stroke", "#BFD8F6") .attr("stroke-width", 1.4); metric.append("line") .attr("x1", metricX + metricW / 2) .attr("x2", metricX + metricW / 2) .attr("y1", metricY + 25) .attr("y2", metricY + metricH - 25) .attr("stroke", "#BFD8F6") .attr("stroke-width", 2);
function addMetric(side, group, color, x0, slotName) { const growth = growthFor(group); const iconSize = Math.min(70, metricH - 38); appendSlot(metric, { slot: slotName, className: `${side}-growth-icon-slot`, x: x0 + 42, y: metricY + (metricH - iconSize) / 2, size: iconSize, fill: side === "left" ? "#E2F4D9" : "#E4F0FF", stroke: side === "left" ? "#C8E7BC" : "#C7DCF8", dash: "6 5", anchor: `${side}-growth-metric-strip`, collision: "stay-inside-growth-strip-and-below-plot", label: "", textColor: color }); const labelX = x0 + 138; const topText = growth ? `${growth.firstDim} \u2192 ${growth.lastDim} GROWTH` : "GROWTH"; metric.append("text") .attr("x", labelX) .attr("y", metricY + 42) .attr("font-family", "Arial, sans-serif") .attr("font-size", 21) .attr("font-weight", 800) .attr("fill", "#344051") .text(topText); metric.append("text") .attr("x", labelX) .attr("y", metricY + 92) .attr("font-family", "Arial Narrow, Arial, sans-serif") .attr("font-size", 45) .attr("font-weight", 900) .attr("fill", color) .text(growth ? `${growth.pct >= 0 ? "+" : ""}${Math.round(growth.pct)}%` : ""); const groupLabelX = labelX + 160; const groupLabelMaxWidth = side === "left" ? Math.max(70, x0 + metricW / 2 - groupLabelX - 28) : Math.max(70, metricX + metricW - groupLabelX - 28); const metricGroupFontSize = fittedFontSize(String(group), groupLabelMaxWidth, 25, 13, 0.56); metric.append("text") .attr("x", groupLabelX) .attr("y", metricY + 92) .attr("font-family", "Arial, sans-serif") .attr("font-size", metricGroupFontSize) .attr("font-weight", 500) .attr("fill", color) .text(String(group)); }
addMetric("left", leftGroup, leftColor, metricX, "growth-icon-left"); addMetric("right", rightGroup, rightColor, metricX + metricW / 2, "growth-icon-right");
return svg.node();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524/*REQUIREMENTS_BEGIN{ "chart_type": "Horizontal Diverging Bar Chart", "chart_name": "horizontal_diverging_bar_chart_08", "chart_for": "comparison", "is_composite": false, "required_fields": ["x", "y", "group"], "required_fields_type": [["categorical"], ["numerical"], ["categorical"]], "required_fields_range": [[2, 20], [0, "inf"], [2, 2]], "required_fields_icons": ["x"], "required_other_icons": [], "required_fields_colors": ["group"], "required_other_colors": ["primary"], "supported_effects": ["shadow", "radius_corner", "gradient", "stroke", "spacing"], "min_height": 400, "min_width": 400, "background": "styled", "icon_mark": "none", "icon_label": "side", "has_x_axis": "no", "has_y_axis": "no"}REQUIREMENTS_END*/
function makeChart(containerSelector, data) { const rootData = data || {}; const chartData = Array.isArray(rootData.data?.data) ? rootData.data.data : (Array.isArray(rootData.data) ? rootData.data : []); const variables = rootData.variables || {}; const typography = rootData.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" } }; const colorResolver = chartUtils.color.resolver(rootData);
d3.select(containerSelector).html("");
const width = Number(variables.width) || 800; const height = Number(variables.height) || 600; const labelFamily = typography.label?.font_family || "Arial"; const valueFamily = typography.annotation?.font_family || labelFamily; const textColor = colorResolver.text({ fallback: "#101828" }).value; const mutedText = colorResolver.variant(textColor, { mode: "brighter", amount: 2.8 }); const leftAccent = colorResolver.other("left_accent", { fallback: "#F59E0B" }).value || "#F59E0B"; const rightAccent = colorResolver.other("right_accent", { fallback: "#E84D67" }).value || "#E84D67"; const centerAccent = "#5B78F6";
function schemaChannel(channel, fallback) { try { return chartUtils.schema.channel(rootData, channel); } catch (error) { return fallback; } }
const dimensionChannel = schemaChannel("x", { key: "category", unit: "" }); const valueChannel = schemaChannel("y", { key: "value", unit: "" }); const groupChannel = schemaChannel("group", { key: "group", unit: "" }); const dimensionField = dimensionChannel.key; const valueField = valueChannel.key; const groupField = groupChannel.key; const valueUnit = valueChannel.unit || ""; const dimensionLabel = (dimensionChannel.name || dimensionField || "Category").replace(/([a-z])([A-Z])/g, "$1 $2");
const rawGroups = [...new Set(chartData.map(d => d[groupField]).filter(d => d != null))]; if (rawGroups.length < 2 || chartData.length === 0) { return d3.select(containerSelector).append("svg") .attr("width", "100%") .attr("height", height) .attr("viewBox", `0 0 ${width} ${height}`) .node(); }
const leftGroup = rawGroups[0]; const rightGroup = rawGroups[1]; const allDimensions = [...new Set(chartData.map(d => d[dimensionField]).filter(d => d != null))]; const leftRank = new Map(chartData .filter(d => d[groupField] === leftGroup) .map(d => [d[dimensionField], Number(d[valueField]) || 0])); const dimensions = allDimensions.slice().sort((a, b) => { const diff = (leftRank.get(b) || 0) - (leftRank.get(a) || 0); return diff !== 0 ? diff : String(a).localeCompare(String(b)); });
const rowByDimension = dimensions.map((dimension) => { const left = chartData.find(d => d[dimensionField] === dimension && d[groupField] === leftGroup); const right = chartData.find(d => d[dimensionField] === dimension && d[groupField] === rightGroup); return { dimension, leftValue: left ? Number(left[valueField]) || 0 : 0, rightValue: right ? Number(right[valueField]) || 0 : 0, leftDatum: left || null, rightDatum: right || null }; });
const maxLeftValue = Math.max(1, d3.max(rowByDimension, d => d.leftValue) || 1); const maxRightValue = Math.max(1, d3.max(rowByDimension, d => d.rightValue) || 1);
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("data-template", "horizontal_diverging_bar_chart_08") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true");
const defs = svg.append("defs"); const shadow = defs.append("filter") .attr("id", "hdbc08-soft-shadow") .attr("x", "-20%") .attr("y", "-20%") .attr("width", "140%") .attr("height", "150%"); shadow.append("feDropShadow") .attr("dx", 0) .attr("dy", 4) .attr("stdDeviation", 5) .attr("flood-color", "#9AA4B2") .attr("flood-opacity", 0.18);
const leftGradient = defs.append("linearGradient") .attr("id", "hdbc08-left-gradient") .attr("x1", "0%") .attr("x2", "100%") .attr("y1", "0%") .attr("y2", "0%"); leftGradient.append("stop").attr("offset", "0%").attr("stop-color", "#FDBA3B"); leftGradient.append("stop").attr("offset", "100%").attr("stop-color", leftAccent);
const rightGradient = defs.append("linearGradient") .attr("id", "hdbc08-right-gradient") .attr("x1", "0%") .attr("x2", "100%") .attr("y1", "0%") .attr("y2", "0%"); rightGradient.append("stop").attr("offset", "0%").attr("stop-color", "#EF6275"); rightGradient.append("stop").attr("offset", "100%").attr("stop-color", rightAccent);
const marginX = Math.max(24, width * 0.045); const marginTop = Math.max(10, height * 0.018); const marginBottom = Math.max(14, height * 0.025); const headerH = Math.max(46, Math.min(68, height * 0.105)); const headerGap = Math.max(9, height * 0.018); const plotX = marginX; const plotW = width - marginX * 2; const plotY = marginTop; const rowsY = plotY + headerH + headerGap; const rowsH = height - rowsY - marginBottom; const n = Math.max(1, rowByDimension.length); const rowGap = Math.max(3, Math.min(7, rowsH / n * 0.09)); const rowH = Math.max(20, (rowsH - rowGap * (n - 1)) / n); const dense = rowH < 40; let valueFont = Math.max(10, Math.min(22, rowH * (dense ? 0.34 : 0.44))); const labelFont = Math.max(8, Math.min(16, rowH * (dense ? 0.28 : 0.32))); const headerFont = Math.max(8, Math.min(13, headerH * 0.22)); const iconR = Math.max(8, Math.min(22, rowH * 0.33)); const barH = Math.max(5, Math.min(24, rowH * 0.28)); const barRadius = Math.max(2, Math.min(4, barH * 0.18));
const formatValue = (value) => { const formatted = chartUtils.format.autoText(value); return valueUnit ? `${formatted}${valueUnit}` : `${formatted}`; };
const measure = (value, fontSize, family = valueFamily, weight = 700) => { return chartUtils.text.measure(null, String(value), { fontFamily: family, fontSize, fontWeight: weight }).width; };
const maxLeftLabelWRaw = d3.max(rowByDimension, d => measure(formatValue(d.leftValue), valueFont)) || 0; const maxRightLabelWRaw = d3.max(rowByDimension, d => measure(formatValue(d.rightValue), valueFont)) || 0; const maxValueReserve = plotW * (dense ? 0.15 : 0.18); const rawMaxValueW = Math.max(maxLeftLabelWRaw, maxRightLabelWRaw); if (rawMaxValueW > maxValueReserve) { valueFont = Math.max(9, valueFont * Math.max(0.62, maxValueReserve / rawMaxValueW)); } const maxLeftLabelW = d3.max(rowByDimension, d => measure(formatValue(d.leftValue), valueFont)) || 0; const maxRightLabelW = d3.max(rowByDimension, d => measure(formatValue(d.rightValue), valueFont)) || 0; const gap = Math.max(8, plotW * 0.012); const leftValueW = Math.min(plotW * 0.19, Math.max(plotW * 0.10, maxLeftLabelW + 12)); const rightValueW = Math.min(plotW * 0.19, Math.max(plotW * 0.10, maxRightLabelW + 12)); const centerW = Math.min(plotW * 0.36, Math.max(plotW * 0.30, plotW * (dense ? 0.31 : 0.34))); const barW = Math.max(36, (plotW - leftValueW - rightValueW - centerW - gap * 4) / 2); const centerX = plotX + leftValueW + gap + barW + gap; const col = { leftValueX: plotX + leftValueW - 4, leftBarX: plotX + leftValueW + gap, leftBarW: barW, centerX: centerX, centerW: centerW, rightBarX: centerX + centerW + gap, rightBarW: barW, rightValueX: centerX + centerW + gap + barW + gap };
const truncate = (value, maxWidth, fontSize, weight = 700) => { return chartUtils.text.truncate(String(value), maxWidth, { fontFamily: labelFamily, fontSize, fontWeight: weight }); };
const headerLabel = (value) => String(value) .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/\s+/g, " ") .trim() .toUpperCase(); const textLengthOrNull = (value, maxWidth, fontSize, family = labelFamily, weight = 800) => { const w = measure(value, fontSize, family, weight); return w > maxWidth ? maxWidth : null; }; const splitHeaderLines = (text, maxChars = 14) => { const words = String(text || "").split(/\s+/).filter(Boolean); if (words.join(" ").length <= maxChars || words.length <= 1) return [words.join(" ")]; const lines = []; let current = ""; words.forEach((word) => { if (!current) { current = word; } else if ((current + " " + word).length <= maxChars || lines.length >= 1) { current += " " + word; } else { lines.push(current); current = word; } }); if (current) lines.push(current); return lines.slice(0, 2); }; const appendHeaderText = (parent, cfg) => { const lines = splitHeaderLines(cfg.text, cfg.maxChars); const fontSize = lines.length > 1 ? Math.max(7, headerFont * 0.72) : headerFont; const text = parent.append("text") .attr("x", cfg.x) .attr("y", cfg.y) .attr("text-anchor", cfg.anchor || "start") .attr("fill", cfg.fill) .attr("font-family", labelFamily) .attr("font-size", fontSize) .attr("font-weight", 800) .attr("letter-spacing", lines.length > 1 ? 0.15 : (cfg.letterSpacing ?? 0.5)); lines.forEach((line, i) => { text.append("tspan") .attr("x", cfg.x) .attr("dy", i === 0 ? (lines.length > 1 ? "-0.18em" : "0.35em") : "1.18em") .text(line); }); return text; }; const leftHeaderText = headerLabel(leftGroup); const centerHeaderText = headerLabel(dimensionLabel); const rightHeaderText = headerLabel(rightGroup); const centerHeaderMaxW = plotW * 0.25;
const table = svg.append("g") .attr("class", "reference-card-table") .attr("data-reference-local-geometry", "grid-aligned-row-cards-shared-centerlines");
table.append("rect") .attr("class", "chart-panel") .attr("x", plotX - 2) .attr("y", plotY - 2) .attr("width", plotW + 4) .attr("height", height - plotY - marginBottom + 4) .attr("rx", 18) .attr("ry", 18) .attr("fill", "#FFFFFF") .attr("stroke", "#E6EAF2") .attr("stroke-width", 1) .style("filter", "url(#hdbc08-soft-shadow)");
const header = table.append("g") .attr("class", "segmented-header") .attr("data-coordinate-relationship", "flush-with-row-card-grid"); header.append("rect") .attr("x", plotX + 8) .attr("y", plotY + 6) .attr("width", plotW - 16) .attr("height", headerH - 12) .attr("rx", (headerH - 12) / 2) .attr("ry", (headerH - 12) / 2) .attr("fill", "#FFF6E3") .attr("stroke", "#F3E9D6"); header.append("rect") .attr("x", plotX + plotW * 0.35) .attr("y", plotY + 6) .attr("width", plotW * 0.30) .attr("height", headerH - 12) .attr("rx", (headerH - 12) / 2) .attr("ry", (headerH - 12) / 2) .attr("fill", "#FFFFFF") .attr("stroke", "#EEF1F6") .style("filter", "url(#hdbc08-soft-shadow)"); header.append("rect") .attr("x", plotX + plotW * 0.62) .attr("y", plotY + 6) .attr("width", plotW * 0.38 - 8) .attr("height", headerH - 12) .attr("rx", (headerH - 12) / 2) .attr("ry", (headerH - 12) / 2) .attr("fill", "#FDECF0") .attr("stroke", "#F7D5DC");
function drawLegendIcon(group, cx, cy, side) { const accent = side === "left" ? leftAccent : rightAccent; header.append("circle") .attr("cx", cx) .attr("cy", cy) .attr("r", Math.max(11, headerH * 0.24)) .attr("fill", "#FFFFFF") .attr("stroke", accent) .attr("stroke-width", 1.3); header.append("path") .attr("d", side === "left" ? `M ${cx - 6} ${cy + 5} C ${cx - 2} ${cy - 5}, ${cx + 2} ${cy - 8}, ${cx + 7} ${cy - 10} C ${cx + 5} ${cy - 2}, ${cx + 1} ${cy + 4}, ${cx - 6} ${cy + 5} Z` : `M ${cx - 7} ${cy - 4} L ${cx + 2} ${cy - 8} L ${cx + 2} ${cy + 8} L ${cx - 7} ${cy + 4} Z M ${cx + 4} ${cy - 4} L ${cx + 8} ${cy - 2} L ${cx + 8} ${cy + 2} L ${cx + 4} ${cy + 4} Z`) .attr("fill", accent) .attr("opacity", 0.9); }
const headerCy = plotY + headerH / 2; drawLegendIcon(leftGroup, plotX + plotW * 0.11, headerCy, "left"); drawLegendIcon(rightGroup, plotX + plotW * 0.74, headerCy, "right");
appendHeaderText(header, { x: plotX + plotW * 0.18, y: headerCy, text: leftHeaderText, fill: leftAccent, maxChars: 14, letterSpacing: 0.5 }); header.append("text") .attr("x", plotX + plotW * 0.50) .attr("y", headerCy) .attr("dy", "0.35em") .attr("text-anchor", "middle") .attr("fill", "#384152") .attr("font-family", labelFamily) .attr("font-size", headerFont) .attr("font-weight", 800) .attr("letter-spacing", 0.7) .attr("textLength", textLengthOrNull(centerHeaderText, centerHeaderMaxW, headerFont)) .attr("lengthAdjust", textLengthOrNull(centerHeaderText, centerHeaderMaxW, headerFont) ? "spacingAndGlyphs" : null) .text(centerHeaderText); appendHeaderText(header, { x: plotX + plotW * 0.89, y: headerCy, text: rightHeaderText, fill: rightAccent, anchor: "middle", maxChars: 8, letterSpacing: 0.5 });
const rows = table.selectAll(".comparison-row") .data(rowByDimension) .enter() .append("g") .attr("class", "comparison-row") .attr("data-coordinate-relationship", "grid-aligned-row-centerline") .attr("data-category", d => d.dimension) .attr("transform", (d, i) => `translate(0,${rowsY + i * (rowH + rowGap)})`);
rows.append("rect") .attr("class", "row-card") .attr("x", plotX) .attr("y", 0) .attr("width", plotW) .attr("height", rowH) .attr("rx", Math.min(14, rowH * 0.22)) .attr("ry", Math.min(14, rowH * 0.22)) .attr("fill", "#FFFFFF") .attr("stroke", "#E9EDF5") .attr("stroke-width", 1) .style("filter", rowH >= 30 ? "url(#hdbc08-soft-shadow)" : "none");
rows.append("line") .attr("x1", col.centerX - gap * 0.8) .attr("x2", col.centerX - gap * 0.8) .attr("y1", 2) .attr("y2", rowH - 2) .attr("stroke", "#E5EAF2") .attr("stroke-width", 1) .attr("stroke-dasharray", "3 3") .attr("opacity", dense ? 0.35 : 0.65); rows.append("line") .attr("x1", col.centerX + col.centerW + gap * 0.8) .attr("x2", col.centerX + col.centerW + gap * 0.8) .attr("y1", 2) .attr("y2", rowH - 2) .attr("stroke", "#E5EAF2") .attr("stroke-width", 1) .attr("stroke-dasharray", "3 3") .attr("opacity", dense ? 0.35 : 0.65);
rows.append("text") .attr("class", "left-value-label") .attr("x", col.leftValueX) .attr("y", rowH / 2) .attr("dy", "0.35em") .attr("text-anchor", "end") .attr("fill", leftAccent) .attr("font-family", valueFamily) .attr("font-size", valueFont) .attr("font-weight", 700) .text(d => formatValue(d.leftValue));
rows.append("rect") .attr("class", "left-bar") .attr("data-group", String(leftGroup)) .attr("data-value", d => d.leftValue) .attr("data-bar-endpoint-geometry", "slight-rounded-rectangle-not-pill") .attr("x", d => col.leftBarX + col.leftBarW - (d.leftValue / maxLeftValue) * col.leftBarW) .attr("y", rowH / 2 - barH / 2) .attr("width", d => Math.max(d.leftValue > 0 ? 3 : 0, (d.leftValue / maxLeftValue) * col.leftBarW)) .attr("height", barH) .attr("rx", barRadius) .attr("ry", barRadius) .attr("fill", "url(#hdbc08-left-gradient)");
const iconGroup = rows.append("g") .attr("class", "category-icon-slot") .attr("data-asset-slot", "category-icon") .attr("data-slot-policy", "image2_asset_with_neutral_placeholder") .attr("data-anchor", "row-centerline-before-category-label") .attr("data-collision-rule", "inside-center-column-left-of-label-avoid-bars-values-dividers") .attr("data-no-embedded-raster", "true") .attr("data-no-copied-reference-art", "true") .attr("data-slot-bbox", d => { const cx = col.centerX + iconR + 2; const cy = rowH / 2; return `${Math.round(cx - iconR)},${Math.round(cy - iconR)},${Math.round(iconR * 2)},${Math.round(iconR * 2)}`; });
iconGroup.append("circle") .attr("cx", col.centerX + iconR + 2) .attr("cy", rowH / 2) .attr("r", iconR) .attr("fill", "#EEF3FF") .attr("stroke", "#DFE7FF") .attr("stroke-width", 1);
iconGroup.each(function(d) { const group = d3.select(this); const cx = col.centerX + iconR + 2; const cy = rowH / 2; group.append("text") .attr("x", cx) .attr("y", cy) .attr("dy", "0.36em") .attr("text-anchor", "middle") .attr("font-family", labelFamily) .attr("font-size", Math.max(7, iconR * 0.85)) .attr("font-weight", 800) .attr("fill", centerAccent) .text(String(d.dimension).charAt(0).toUpperCase()); });
rows.append("text") .attr("class", "category-label") .attr("x", col.centerX + iconR * 2 + 12) .attr("y", rowH / 2) .attr("dy", "0.35em") .attr("fill", "#0F1733") .attr("font-family", labelFamily) .attr("font-size", labelFont) .attr("font-weight", 800) .attr("textLength", d => textLengthOrNull( String(d.dimension), Math.max(12, col.centerW - iconR * 2 - 18), labelFont, labelFamily, 800 )) .attr("lengthAdjust", d => textLengthOrNull( String(d.dimension), Math.max(12, col.centerW - iconR * 2 - 18), labelFont, labelFamily, 800 ) ? "spacingAndGlyphs" : null) .text(d => String(d.dimension));
rows.append("rect") .attr("class", "right-bar") .attr("data-group", String(rightGroup)) .attr("data-value", d => d.rightValue) .attr("data-bar-endpoint-geometry", "slight-rounded-rectangle-not-pill") .attr("x", col.rightBarX) .attr("y", rowH / 2 - barH / 2) .attr("width", d => Math.max(d.rightValue > 0 ? 3 : 0, (d.rightValue / maxRightValue) * col.rightBarW)) .attr("height", barH) .attr("rx", barRadius) .attr("ry", barRadius) .attr("fill", "url(#hdbc08-right-gradient)");
rows.append("text") .attr("class", "right-value-label") .attr("x", d => Math.min(col.rightValueX, col.rightBarX + (d.rightValue / maxRightValue) * col.rightBarW + 10)) .attr("y", rowH / 2) .attr("dy", "0.35em") .attr("fill", rightAccent) .attr("font-family", valueFamily) .attr("font-size", valueFont) .attr("font-weight", 700) .text(d => formatValue(d.rightValue));
return svg.node();}modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_0.jsAdded+464
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_0_test.jsAdded+369
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_0_weilai.jsAdded+318
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_1.jsAdded+361
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_10.jsAdded+859
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_11.jsAdded+574
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_12.jsAdded+719
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_13.jsAdded+531
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_14.jsAdded+736
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_15.jsAdded+444
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_15_hand.jsAdded+483
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_16.jsAdded+630
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_17.jsAdded+617
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_18.jsAdded+356
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_19.jsAdded+326
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_2.jsAdded+216
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_20.jsAdded+405
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_21.jsAdded+615
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_22.jsAdded+522
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_23.jsAdded+724
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_24.jsAdded+397
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_25.jsAdded+332
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_26.jsAdded+434
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_27.jsAdded+435
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_28.jsAdded+588
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_29.jsAdded+589
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_2_hand.jsAdded+234
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_3.jsAdded+224
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_30.jsAdded+440
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_33.jsAdded+603
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_4.jsAdded+525
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_4_hand.jsAdded+584
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_5.jsAdded+384
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_5_hand.jsAdded+407
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_6.jsAdded
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_7.jsAdded+410
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_8.jsAdded+677
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_bar_chart_9.jsAdded+406
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_01.jsAdded+592
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_01_hand.jsAdded+453
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_02.jsAdded+678
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_03.jsAdded+718
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_04.jsAdded+576
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_04_hand.jsAdded+584
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_05.jsAdded+767
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_06.jsAdded+687
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_07.jsAdded+747
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_08.jsAdded+524
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_09.jsAdded
modules/chart_engine/template/d3-js/bar_chart_horizontal/horizontal_diverging_bar_chart_10.jsAdded