@opendata-ai/openchart-engine 6.24.1 → 6.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/compile.ts CHANGED
@@ -19,6 +19,8 @@ import type {
19
19
  ChartSpec,
20
20
  CompileOptions,
21
21
  CompileTableOptions,
22
+ DataRow,
23
+ Encoding,
22
24
  EncodingChannel,
23
25
  LayerSpec,
24
26
  Mark,
@@ -33,6 +35,7 @@ import type {
33
35
  import {
34
36
  adaptTheme,
35
37
  computeLabelBounds,
38
+ estimateTextWidth,
36
39
  generateAltText,
37
40
  generateDataTable,
38
41
  getBreakpoint,
@@ -40,6 +43,8 @@ import {
40
43
  getLayoutStrategy,
41
44
  resolveTheme,
42
45
  } from '@opendata-ai/openchart-core';
46
+ import { scaleLinear } from 'd3-scale';
47
+ import { curveMonotoneX, area as d3area, line as d3line } from 'd3-shape';
43
48
  import { computeAnnotations } from './annotations/compute';
44
49
  // Side-effect import: registers all built-in chart renderers with the
45
50
  // registry on module load. Tests that clear the registry can import
@@ -338,8 +343,9 @@ export function compileChart(spec: unknown, options: CompileOptions): ChartLayou
338
343
 
339
344
  // INVARIANT 3 — post-hoc defaultColor: must run AFTER computeScales since resolution needs
340
345
  // theme context. Do not move into computeScales (would require threading theme through).
341
- // If the user set a fill on the mark def, it takes priority over the theme's first categorical.
342
- scales.defaultColor = chartSpec.markDef.fill ?? theme.colors.categorical[0];
346
+ // fill wins for bar/area/arc marks; stroke wins for line marks (the stroke IS the color).
347
+ scales.defaultColor =
348
+ chartSpec.markDef.fill ?? chartSpec.markDef.stroke ?? theme.colors.categorical[0];
343
349
 
344
350
  // Arc charts (pie/donut) don't use axes or gridlines
345
351
  const isRadial = chartSpec.markType === 'arc';
@@ -473,13 +479,15 @@ export function compileLayer(spec: LayerSpec, options: CompileOptions): ChartLay
473
479
  return compileChart(singleSpec, options);
474
480
  }
475
481
 
476
- // Build primary spec with unioned data for shared scale computation.
477
- // The primary layout provides chrome, axes, dimensions, legend, and a11y.
482
+ // Branch: independent y-scales produce dual-axis layout
483
+ if (spec.resolve?.scale?.y === 'independent') {
484
+ return compileLayerIndependent(leaves, spec, options);
485
+ }
486
+
487
+ // Shared scales (default): union data and compile together
478
488
  const primarySpec = buildPrimarySpec(leaves, spec);
479
489
  const primaryLayout = compileChart(primarySpec, options);
480
490
 
481
- // Compile each leaf layer independently but with the full unioned data
482
- // so they all share the same scale domains.
483
491
  const allMarks: Mark[] = [];
484
492
  const seenLabels = new Set<string>();
485
493
  const mergedLegendEntries = [...primaryLayout.legend.entries];
@@ -488,14 +496,10 @@ export function compileLayer(spec: LayerSpec, options: CompileOptions): ChartLay
488
496
  }
489
497
 
490
498
  for (const leaf of leaves) {
491
- // Compile each leaf with its own data so marks correspond to its rows only.
492
- // Scale domains may differ slightly between layers, but this prevents
493
- // duplicate marks from feeding unioned data into every renderer.
494
499
  const leafLayout = compileChart(leaf as unknown, options);
495
500
 
496
501
  allMarks.push(...leafLayout.marks);
497
502
 
498
- // Deduplicate legend entries across layers
499
503
  for (const entry of leafLayout.legend.entries) {
500
504
  if (!seenLabels.has(entry.label)) {
501
505
  seenLabels.add(entry.label);
@@ -514,6 +518,434 @@ export function compileLayer(spec: LayerSpec, options: CompileOptions): ChartLay
514
518
  };
515
519
  }
516
520
 
521
+ // ---------------------------------------------------------------------------
522
+ // Independent y-scale compilation (dual-axis charts)
523
+ // ---------------------------------------------------------------------------
524
+
525
+ /**
526
+ * Estimate the pixel width needed for a right-side y-axis based on data values.
527
+ * Mirrors the left-margin estimation logic in computeDimensions.
528
+ */
529
+ function estimateYAxisLabelWidth(
530
+ data: DataRow[],
531
+ encoding: Encoding | undefined,
532
+ baseFontSize: number,
533
+ ): number {
534
+ if (!encoding?.y) return 40;
535
+ const yEnc = encoding.y;
536
+ const yField = yEnc.field;
537
+ if (!yField) return 40;
538
+
539
+ const yType = yEnc.type;
540
+ if (yType === 'nominal' || yType === 'ordinal') {
541
+ let maxWidth = 0;
542
+ for (const row of data) {
543
+ const label = String(row[yField] ?? '');
544
+ const w = estimateTextWidth(label, baseFontSize, 400);
545
+ if (w > maxWidth) maxWidth = w;
546
+ }
547
+ return maxWidth > 0 ? maxWidth + 10 : 40;
548
+ }
549
+
550
+ // Quantitative/temporal: estimate from the largest value
551
+ let maxAbsVal = 0;
552
+ for (const row of data) {
553
+ const v = Number(row[yField]);
554
+ if (Number.isFinite(v) && Math.abs(v) > maxAbsVal) maxAbsVal = Math.abs(v);
555
+ }
556
+ let sampleLabel: string;
557
+ if (maxAbsVal >= 1_000_000_000) sampleLabel = '1.5B';
558
+ else if (maxAbsVal >= 1_000_000) sampleLabel = '1.5M';
559
+ else if (maxAbsVal >= 1_000) sampleLabel = '1.5K';
560
+ else if (maxAbsVal >= 100) sampleLabel = '100';
561
+ else if (maxAbsVal >= 10) sampleLabel = '10';
562
+ else sampleLabel = '0.0';
563
+ const hasNeg = data.some((r) => Number(r[yField]) < 0);
564
+ const labelEst = (hasNeg ? '-' : '') + sampleLabel;
565
+ return estimateTextWidth(labelEst, baseFontSize, 400) + 10;
566
+ }
567
+
568
+ /**
569
+ * Compile a LayerSpec with independent y-scales (dual-axis chart).
570
+ *
571
+ * Layer 0 gets the left y-axis, layer 1 gets the right y-axis.
572
+ * Both layers share the x-axis. Limited to exactly 2 layers.
573
+ */
574
+ function compileLayerIndependent(
575
+ leaves: ChartSpec[],
576
+ layerSpec: LayerSpec,
577
+ options: CompileOptions,
578
+ ): ChartLayout {
579
+ if (leaves.length > 2) {
580
+ throw new Error(
581
+ 'Independent y-scales support at most 2 layers (left and right y-axis). ' +
582
+ `Got ${leaves.length} layers.`,
583
+ );
584
+ }
585
+
586
+ const leaf0 = leaves[0];
587
+ const leaf1 = leaves[1];
588
+
589
+ // Validate x-field types are compatible
590
+ const xType0 = leaf0.encoding?.x?.type;
591
+ const xType1 = leaf1.encoding?.x?.type;
592
+ if (xType0 && xType1 && xType0 !== xType1) {
593
+ throw new Error(
594
+ `Dual-axis charts require matching x-field types across layers. ` +
595
+ `Layer 0 has '${xType0}', layer 1 has '${xType1}'.`,
596
+ );
597
+ }
598
+
599
+ // Estimate right-axis label width to reserve margin space
600
+ const theme = resolveTheme(layerSpec.theme ?? leaf1.theme);
601
+ const axisFontSize = theme.fonts?.sizes?.axisTick ?? 11;
602
+ const rightAxisWidth = estimateYAxisLabelWidth(leaf1.data, leaf1.encoding, axisFontSize);
603
+ // Add space for the rotated axis title if present (match left-axis 45px clearance)
604
+ const hasRightAxisTitle = !!leaf1.encoding?.y?.axis?.title;
605
+ const rightReserve = rightAxisWidth + (hasRightAxisTitle ? 45 : 0);
606
+
607
+ const optionsWithReserve: CompileOptions = {
608
+ ...options,
609
+ rightAxisReserve: rightReserve,
610
+ };
611
+
612
+ // Union x-data so both layers see the full x-domain.
613
+ // Each layer keeps its own y-data for independent y-scales.
614
+ const xField0 = leaf0.encoding?.x?.field;
615
+ const xField1 = leaf1.encoding?.x?.field;
616
+ const unionXValues = new Set<unknown>();
617
+ if (xField0) for (const row of leaf0.data) unionXValues.add(row[xField0]);
618
+ if (xField1) for (const row of leaf1.data) unionXValues.add(row[xField1]);
619
+
620
+ // Add missing x-values from leaf1 into leaf0's data as stub rows,
621
+ // and vice versa, so both scales see the full x-domain.
622
+ let leaf0WithUnionX = ensureXDomainCoverage(leaf0, xField0, unionXValues);
623
+ let leaf1WithUnionX = ensureXDomainCoverage(leaf1, xField1, unionXValues);
624
+
625
+ // Align y-domains so zero maps to the same pixel position on both axes
626
+ const aligned = alignYDomains(leaf0WithUnionX, leaf1WithUnionX);
627
+ if (aligned) {
628
+ leaf0WithUnionX = withYDomain(leaf0WithUnionX, aligned.domain0);
629
+ leaf1WithUnionX = withYDomain(leaf1WithUnionX, aligned.domain1);
630
+ }
631
+
632
+ // Compile layer 0 as the primary layout (chrome, x-axis, left y-axis)
633
+ const primary0 = buildPrimarySpec([leaf0WithUnionX], layerSpec);
634
+ const layout0 = compileChart(primary0, optionsWithReserve);
635
+
636
+ // Compile layer 1 independently for its own y-axis and marks.
637
+ // Keep chrome identical to layer 0 so both compile against the same chart area dimensions.
638
+ // layout1's chrome is never rendered -- we spread layout0 into the final return value.
639
+ const primary1 = buildPrimarySpec([leaf1WithUnionX], layerSpec);
640
+ primary1.annotations = [];
641
+ const layout1 = compileChart(primary1, optionsWithReserve);
642
+
643
+ // Extract layer 1's y-axis, reposition it to the right side
644
+ const y2Axis = layout1.axes.y
645
+ ? {
646
+ ...layout1.axes.y,
647
+ orient: 'right' as const,
648
+ gridlines: [], // Only left y-axis produces gridlines
649
+ start: {
650
+ x: layout0.area.x + layout0.area.width,
651
+ y: layout0.area.y,
652
+ },
653
+ end: {
654
+ x: layout0.area.x + layout0.area.width,
655
+ y: layout0.area.y + layout0.area.height,
656
+ },
657
+ }
658
+ : undefined;
659
+
660
+ // Build a per-category x-position map from whichever layer uses a band scale (bars).
661
+ // Band-scale tick positions are band centers -- the canonical x positions that both
662
+ // layers should align to. Line/area marks use a point scale and land at different pixels.
663
+ // We remap line/area mark x-coordinates by looking up each data row's x-field value
664
+ // in the band-center map, replacing point-scale positions with exact band centers.
665
+ const layer0HasBars = layout0.marks.some((m) => m.type === 'rect');
666
+ const layer1HasBars = layout1.marks.some((m) => m.type === 'rect');
667
+
668
+ // Build category → band-center-pixel map from the bar layer's x-axis ticks
669
+ const bandCenterByCategory = new Map<string, number>();
670
+ if (layer0HasBars && layout0.axes.x?.ticks) {
671
+ for (const tick of layout0.axes.x.ticks) {
672
+ bandCenterByCategory.set(String(tick.label), tick.position);
673
+ }
674
+ } else if (layer1HasBars && layout1.axes.x?.ticks) {
675
+ for (const tick of layout1.axes.x.ticks) {
676
+ bandCenterByCategory.set(String(tick.label), tick.position);
677
+ }
678
+ }
679
+
680
+ // Remap line/area/point mark x-coordinates to band centers using data rows.
681
+ // The SVG path strings are kept as-is (the smooth curve is close enough to correct
682
+ // after a small x-shift). Only the discrete coordinate arrays and dot positions
683
+ // are remapped so tooltips and point markers land on bar centers.
684
+ const remapMarkX = (xField: string | undefined, mark: Mark): Mark => {
685
+ if (!xField || bandCenterByCategory.size === 0) return mark;
686
+ if (mark.type === 'line') {
687
+ const newPoints = mark.points.map((p, i) => {
688
+ const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
689
+ return bx !== undefined ? { ...p, x: bx } : p;
690
+ });
691
+ const newDataPoints = mark.dataPoints?.map((dp, i) => {
692
+ const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
693
+ return bx !== undefined ? { ...dp, x: bx } : dp;
694
+ });
695
+ // Regenerate the smooth monotone path from remapped points so the rendered
696
+ // line passes through bar centers with the same curve quality as the original.
697
+ // Uses curveMonotoneX regardless of the original interpolation -- preserving the
698
+ // user-specified curve across x-remapping would require re-resolving the mark's
699
+ // interpolation setting, which isn't stored on LineMark post-compilation.
700
+ const newPath =
701
+ d3line<{ x: number; y: number }>()
702
+ .x((p) => p.x)
703
+ .y((p) => p.y)
704
+ .curve(curveMonotoneX)(newPoints) ?? undefined;
705
+ return { ...mark, points: newPoints, dataPoints: newDataPoints, path: newPath };
706
+ }
707
+ if (mark.type === 'area') {
708
+ const newTopPoints = mark.topPoints.map((p, i) => {
709
+ const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
710
+ return bx !== undefined ? { ...p, x: bx } : p;
711
+ });
712
+ const newBottomPoints = mark.bottomPoints.map((p, i) => {
713
+ const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
714
+ return bx !== undefined ? { ...p, x: bx } : p;
715
+ });
716
+ const newDataPoints = mark.dataPoints?.map((dp, i) => {
717
+ const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
718
+ return bx !== undefined ? { ...dp, x: bx } : dp;
719
+ });
720
+ // Regenerate area fill path and top-line stroke path from remapped points.
721
+ const areaGen = d3area<{ x: number; yTop: number; yBottom: number }>()
722
+ .x((p) => p.x)
723
+ .y0((p) => p.yBottom)
724
+ .y1((p) => p.yTop)
725
+ .curve(curveMonotoneX);
726
+ const topLineGen = d3line<{ x: number; yTop: number }>()
727
+ .x((p) => p.x)
728
+ .y((p) => p.yTop)
729
+ .curve(curveMonotoneX);
730
+ const combined = newTopPoints.map((tp, i) => ({
731
+ x: tp.x,
732
+ yTop: tp.y,
733
+ yBottom: newBottomPoints[i]?.y ?? tp.y,
734
+ }));
735
+ const newPath = areaGen(combined) ?? '';
736
+ const newTopPath = topLineGen(combined) ?? '';
737
+ return {
738
+ ...mark,
739
+ topPoints: newTopPoints,
740
+ bottomPoints: newBottomPoints,
741
+ dataPoints: newDataPoints,
742
+ path: newPath,
743
+ topPath: newTopPath,
744
+ };
745
+ }
746
+ if (mark.type === 'point') {
747
+ const bx = bandCenterByCategory.get(String(mark.data[xField] ?? ''));
748
+ return bx !== undefined ? { ...mark, cx: bx } : mark;
749
+ }
750
+ return mark;
751
+ };
752
+
753
+ // Apply remapping to whichever layer has line/area marks (point scale)
754
+ const adjustedMarks0 =
755
+ bandCenterByCategory.size > 0 && !layer0HasBars
756
+ ? layout0.marks.map((m) => remapMarkX(xField0, m))
757
+ : layout0.marks;
758
+
759
+ // Tag layer 1 marks with yScale: 'y2' and remap x if needed
760
+ const taggedMarks1 = layout1.marks.map((mark) => {
761
+ const tagged = { ...mark, yScale: 'y2' as const };
762
+ if (bandCenterByCategory.size > 0 && !layer1HasBars) {
763
+ return remapMarkX(xField1, tagged) as typeof tagged;
764
+ }
765
+ return tagged;
766
+ });
767
+
768
+ // Merge legend entries with deduplication
769
+ const seenLabels = new Set<string>();
770
+ const mergedLegendEntries = [...layout0.legend.entries];
771
+ for (const entry of mergedLegendEntries) seenLabels.add(entry.label);
772
+ for (const entry of layout1.legend.entries) {
773
+ if (!seenLabels.has(entry.label)) {
774
+ seenLabels.add(entry.label);
775
+ mergedLegendEntries.push(entry);
776
+ }
777
+ }
778
+
779
+ // Merge tooltip descriptors. Layer 1 marks are appended after layer 0's marks,
780
+ // so their render indices start at layout0.marks.length. The descriptor keys
781
+ // for discrete marks (rect, point, arc) are "type-${index}" where index is the
782
+ // mark's position in the final combined array. Re-key them with the correct offset.
783
+ const l0Count = layout0.marks.length;
784
+ const mergedTooltips = new Map(layout0.tooltipDescriptors);
785
+ for (const [key, value] of layout1.tooltipDescriptors) {
786
+ const match = /^(rect|point|arc)-(\d+)$/.exec(key);
787
+ if (match) {
788
+ const offsetKey = `${match[1]}-${Number(match[2]) + l0Count}`;
789
+ mergedTooltips.set(offsetKey, value);
790
+ } else {
791
+ // Line/area tooltips are keyed by series name, not index -- pass through as-is
792
+ mergedTooltips.set(key, value);
793
+ }
794
+ }
795
+
796
+ return {
797
+ ...layout0,
798
+ axes: {
799
+ x: layout0.axes.x,
800
+ y: layout0.axes.y,
801
+ y2: y2Axis,
802
+ },
803
+ marks: [...adjustedMarks0, ...taggedMarks1],
804
+ legend: {
805
+ ...layout0.legend,
806
+ entries: mergedLegendEntries,
807
+ },
808
+ tooltipDescriptors: mergedTooltips,
809
+ };
810
+ }
811
+
812
+ /**
813
+ * Ensure a leaf's data covers the full x-domain by adding stub rows for
814
+ * missing x-values. This keeps scales consistent across layers without
815
+ * injecting scale.domain directly.
816
+ */
817
+ function ensureXDomainCoverage(
818
+ leaf: ChartSpec,
819
+ xField: string | undefined,
820
+ allXValues: Set<unknown>,
821
+ ): ChartSpec {
822
+ if (!xField || allXValues.size === 0) return leaf;
823
+
824
+ const existingXValues = new Set<unknown>();
825
+ for (const row of leaf.data) existingXValues.add(row[xField]);
826
+
827
+ const missingRows: DataRow[] = [];
828
+ for (const xVal of allXValues) {
829
+ if (!existingXValues.has(xVal)) {
830
+ missingRows.push({ [xField]: xVal });
831
+ }
832
+ }
833
+
834
+ if (missingRows.length === 0) return leaf;
835
+
836
+ return {
837
+ ...leaf,
838
+ data: [...leaf.data, ...missingRows],
839
+ };
840
+ }
841
+
842
+ /**
843
+ * Compute aligned y-domains for two layers so that zero maps to the same
844
+ * pixel position on both axes. Returns explicit [min, max] domains for each
845
+ * layer, or undefined if alignment isn't applicable (non-quantitative axes,
846
+ * or neither domain spans zero).
847
+ */
848
+ function alignYDomains(
849
+ leaf0: ChartSpec,
850
+ leaf1: ChartSpec,
851
+ ): { domain0: [number, number]; domain1: [number, number] } | undefined {
852
+ const yEnc0 = leaf0.encoding?.y;
853
+ const yEnc1 = leaf1.encoding?.y;
854
+ if (!yEnc0 || !yEnc1) return undefined;
855
+ if (yEnc0.type !== 'quantitative' || yEnc1.type !== 'quantitative') return undefined;
856
+
857
+ // Skip if either layer has an explicit domain already set by the user
858
+ if (yEnc0.scale?.domain || yEnc1.scale?.domain) return undefined;
859
+
860
+ const includeZero0 = yEnc0.scale?.zero !== false;
861
+ const includeZero1 = yEnc1.scale?.zero !== false;
862
+
863
+ const vals0 = leaf0.data.map((r) => Number(r[yEnc0.field])).filter(Number.isFinite);
864
+ const vals1 = leaf1.data.map((r) => Number(r[yEnc1.field])).filter(Number.isFinite);
865
+ if (vals0.length === 0 || vals1.length === 0) return undefined;
866
+
867
+ // Compute nice domains for each (mirroring buildLinearScale behavior)
868
+ const niced = (vals: number[], includeZero: boolean): [number, number] => {
869
+ let lo = Math.min(...vals);
870
+ let hi = Math.max(...vals);
871
+ if (includeZero) {
872
+ lo = Math.min(0, lo);
873
+ hi = Math.max(0, hi);
874
+ }
875
+ const s = scaleLinear().domain([lo, hi]);
876
+ s.nice();
877
+ const [dLo, dHi] = s.domain();
878
+ return [dLo, dHi];
879
+ };
880
+
881
+ const [min0, max0] = niced(vals0, includeZero0);
882
+ const [min1, max1] = niced(vals1, includeZero1);
883
+
884
+ const span0 = max0 - min0;
885
+ const span1 = max1 - min1;
886
+ if (span0 === 0 || span1 === 0) return undefined;
887
+
888
+ // Zero fraction: how far up from the bottom zero sits (0 = bottom, 1 = top).
889
+ // Only align when BOTH domains naturally contain zero. If one axis is entirely
890
+ // positive or entirely negative (zero is outside the domain), forcing alignment
891
+ // would push the other axis into an unnatural range. In that case, let each
892
+ // axis render its natural domain independently.
893
+ const zf0 = (0 - min0) / span0;
894
+ const zf1 = (0 - min1) / span1;
895
+
896
+ const zeroInDomain0 = zf0 >= -0.001 && zf0 <= 1.001;
897
+ const zeroInDomain1 = zf1 >= -0.001 && zf1 <= 1.001;
898
+ if (!zeroInDomain0 || !zeroInDomain1) return undefined;
899
+
900
+ // If both zeros are at the same position (within tolerance), no adjustment needed
901
+ if (Math.abs(zf0 - zf1) < 0.001) {
902
+ return { domain0: [min0, max0], domain1: [min1, max1] };
903
+ }
904
+
905
+ // Align by extending domains so zero sits at the same proportional position.
906
+ // Keep the niced boundaries on the side that doesn't need extending, and
907
+ // compute the exact extended boundary (no re-nicing) so zero stays locked.
908
+ const targetZf = Math.max(zf0, zf1);
909
+
910
+ const align = (dMin: number, dMax: number, currentZf: number): [number, number] => {
911
+ if (Math.abs(currentZf - targetZf) < 0.001) return [dMin, dMax];
912
+
913
+ if (targetZf > currentZf) {
914
+ // Need more negative range: newMin = -(targetZf / (1 - targetZf)) * dMax
915
+ const newMin = -(targetZf / (1 - targetZf)) * dMax;
916
+ return [newMin, dMax];
917
+ }
918
+ // Need more positive range: newMax = -dMin * (1 - targetZf) / targetZf
919
+ const newMax = (-dMin * (1 - targetZf)) / targetZf;
920
+ return [dMin, newMax];
921
+ };
922
+
923
+ const domain0 = align(min0, max0, zf0);
924
+ const domain1 = align(min1, max1, zf1);
925
+
926
+ return { domain0, domain1 };
927
+ }
928
+
929
+ /**
930
+ * Inject an explicit y-scale domain override into a leaf spec.
931
+ */
932
+ function withYDomain(leaf: ChartSpec, domain: [number, number]): ChartSpec {
933
+ if (!leaf.encoding?.y) return leaf;
934
+ return {
935
+ ...leaf,
936
+ encoding: {
937
+ ...leaf.encoding,
938
+ y: {
939
+ ...leaf.encoding.y,
940
+ scale: {
941
+ ...leaf.encoding.y.scale,
942
+ domain,
943
+ },
944
+ },
945
+ },
946
+ };
947
+ }
948
+
517
949
  /**
518
950
  * Build the primary ChartSpec from all leaves for shared compilation.
519
951
  * Unions all data rows across layers so scales see the full domain.
@@ -314,13 +314,14 @@ export function computeAxes(
314
314
  }
315
315
 
316
316
  const axisTitle = axisConfig?.title;
317
+ const xLabelColor = axisConfig?.labelColor;
317
318
 
318
319
  result.x = {
319
320
  ticks,
320
321
  gridlines: axisConfig?.grid ? gridlines : [],
321
322
  label: axisTitle,
322
- labelStyle: axisLabelStyle,
323
- tickLabelStyle,
323
+ labelStyle: xLabelColor ? { ...axisLabelStyle, fill: xLabelColor } : axisLabelStyle,
324
+ tickLabelStyle: xLabelColor ? { ...tickLabelStyle, fill: xLabelColor } : tickLabelStyle,
324
325
  tickAngle,
325
326
  start: { x: chartArea.x, y: chartArea.y + chartArea.height },
326
327
  end: { x: chartArea.x + chartArea.width, y: chartArea.y + chartArea.height },
@@ -387,14 +388,15 @@ export function computeAxes(
387
388
 
388
389
  const axisTitle = axisConfig?.title;
389
390
  const tickAngle = axisConfig?.labelAngle;
391
+ const yLabelColor = axisConfig?.labelColor;
390
392
 
391
393
  result.y = {
392
394
  ticks,
393
395
  // Y-axis gridlines are shown by default (standard editorial practice)
394
396
  gridlines,
395
397
  label: axisTitle,
396
- labelStyle: axisLabelStyle,
397
- tickLabelStyle,
398
+ labelStyle: yLabelColor ? { ...axisLabelStyle, fill: yLabelColor } : axisLabelStyle,
399
+ tickLabelStyle: yLabelColor ? { ...tickLabelStyle, fill: yLabelColor } : tickLabelStyle,
398
400
  tickAngle,
399
401
  start: { x: chartArea.x, y: chartArea.y },
400
402
  end: { x: chartArea.x, y: chartArea.y + chartArea.height },
@@ -317,6 +317,11 @@ export function computeDimensions(
317
317
  margins.left = Math.max(margins.left, padding + rotatedLabelMargin);
318
318
  }
319
319
 
320
+ // Reserve space for a secondary (right) y-axis in dual-axis charts
321
+ if (options.rightAxisReserve && options.rightAxisReserve > 0) {
322
+ margins.right += options.rightAxisReserve;
323
+ }
324
+
320
325
  // Reserve legend space
321
326
  if (legendLayout.entries.length > 0) {
322
327
  const gap = legendGap(width);