Skip to content

The Open Standard for Generative UI

Scatter chart (#172)

subhambc0467971ffc
diff --git a/js/packages/react-ui/package.json b/js/packages/react-ui/package.json
index 1d521579e..f7f31edc5 100644
--- a/js/packages/react-ui/package.json
+++ b/js/packages/react-ui/package.json
@@ -2,7 +2,7 @@
"type": "module",
"name": "@crayonai/react-ui",
"license": "MIT",
- "version": "0.8.33",
+ "version": "0.8.34",
"description": "Component library for Generative UI SDK",
"main": "dist/index.js",
"types": "dist/index.d.ts",
diff --git a/js/packages/react-ui/src/components/Charts/ScatterChart/ScatterChart.tsx b/js/packages/react-ui/src/components/Charts/ScatterChart/ScatterChart.tsx
new file mode 100644
index 000000000..a527d00b2
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/ScatterChart/ScatterChart.tsx
@@ -0,0 +1,347 @@
+import clsx from "clsx";
+import React, { useEffect, useMemo, useRef, useState } from "react";
+import { Cell, ScatterChart as RechartsScatterChart, Scatter, XAxis, YAxis } from "recharts";
+import { useId } from "../../../polyfills";
+import { ChartConfig, ChartContainer, ChartTooltip } from "../Charts";
+import { SideBarChartData, SideBarTooltipProvider } from "../context/SideBarTooltipContext";
+import { useYAxisLabelWidth } from "../hooks";
+import {
+ CustomTooltipContent,
+ DefaultLegend,
+ gridCartesianGrid,
+ SideBarTooltip,
+ YAxisTick,
+} from "../shared";
+import { LegendItem } from "../types";
+import { get2dChartConfig, getLegendItems } from "../utils/dataUtils";
+import { PaletteName, useChartPalette } from "../utils/PalletUtils";
+import { numberTickFormatter } from "../utils/styleUtils";
+import ScatterDot from "./components/ScatterDot";
+import { ScatterChartData, ScatterPoint } from "./types";
+import {
+ calculateScatterDomain,
+ getScatterDatasets,
+ transformScatterData,
+} from "./utils/ScatterChartUtils";
+
+export interface ScatterChartProps {
+ data: ScatterChartData;
+ xAxisDataKey?: string;
+ yAxisDataKey?: string;
+ theme?: PaletteName;
+ customPalette?: string[];
+ grid?: boolean;
+ legend?: boolean;
+ isAnimationActive?: boolean;
+ xAxisLabel?: React.ReactNode;
+ yAxisLabel?: React.ReactNode;
+ className?: string;
+ height?: number | string;
+ width?: number | string;
+ shape?: "circle" | "square";
+}
+
+const DEFAULT_CHART_HEIGHT = 296;
+const DEFAULT_MARGIN = 20;
+const X_AXIS_HEIGHT = 40;
+
+export const ScatterChart = ({
+ data,
+ xAxisDataKey = "x",
+ yAxisDataKey = "y",
+ theme = "ocean",
+ customPalette,
+ grid = true,
+ xAxisLabel,
+ yAxisLabel,
+ legend = true,
+ isAnimationActive = false,
+ className,
+ height,
+ width,
+ shape = "circle",
+}: ScatterChartProps) => {
+ const datasets = useMemo(() => {
+ return getScatterDatasets(data);
+ }, [data]);
+
+ const colors = useChartPalette({
+ chartThemeName: theme,
+ customPalette,
+ themePaletteName: "lineChartPalette",
+ dataLength: datasets.length,
+ });
+
+ const transformedData: ScatterPoint[] = useMemo(() => {
+ if (!data || !Array.isArray(data)) {
+ return [];
+ }
+ return transformScatterData(data, datasets, colors);
+ }, [data, datasets, colors]);
+
+ const { yAxisWidth, setLabelWidth } = useYAxisLabelWidth(transformedData, [yAxisDataKey]);
+
+ const chartConfig: ChartConfig = useMemo(() => {
+ return get2dChartConfig(
+ datasets,
+ colors,
+ datasets.reduce((acc, key) => ({ ...acc, [key]: key }), {}),
+ undefined,
+ );
+ }, [datasets, colors]);
+
+ const chartWrapperRef = useRef<HTMLDivElement>(null);
+ const legendContainerRef = useRef<HTMLDivElement>(null);
+ const xAxisContainerRef = useRef<HTMLDivElement>(null);
+ const [containerWidth, setContainerWidth] = useState<number>(0);
+ const [isSideBarTooltipOpen, setIsSideBarTooltipOpen] = useState(false);
+ const [isLegendExpanded, setIsLegendExpanded] = useState(false);
+ const [sideBarTooltipData, setSideBarTooltipData] = useState<SideBarChartData>({
+ title: "",
+ values: [],
+ });
+
+ const isFixedNumericHeight = useMemo(() => {
+ if (typeof height === "number") return true;
+ if (typeof height === "string" && height.endsWith("px")) return true;
+ return false;
+ }, [height]);
+
+ const chartHeight = useMemo(() => {
+ if (!chartWrapperRef.current) {
+ return 0;
+ }
+ const legendHeight = legendContainerRef.current?.offsetHeight ?? 0;
+ const xAxisHeight = xAxisContainerRef.current?.offsetHeight ?? 0;
+
+ if (typeof height === "number") {
+ return height - legendHeight - xAxisHeight;
+ }
+
+ return chartWrapperRef.current.offsetHeight - legendHeight - xAxisHeight;
+ }, [containerWidth, height]);
+
+ // Calculate domains for x and y axes
+ const xDomain = useMemo(() => {
+ return calculateScatterDomain(data, xAxisDataKey as "x" | "y");
+ }, [data, xAxisDataKey]);
+
+ const yDomain = useMemo(() => {
+ return calculateScatterDomain(data, yAxisDataKey as "x" | "y");
+ }, [data, yAxisDataKey]);
+
+ const renderDotShape = useMemo(() => {
+ return (props: unknown) => <ScatterDot {...(props as object)} variant={shape} active={false} />;
+ }, [shape]);
+
+ const renderActiveDotShape = useMemo(() => {
+ return (props: unknown) => <ScatterDot {...(props as object)} variant={shape} active />;
+ }, [shape]);
+
+ useEffect(() => {
+ const chartElement = chartWrapperRef.current;
+
+ if (!chartElement) {
+ return;
+ }
+
+ const resizeObserver = new ResizeObserver((entries) => {
+ for (const entry of entries) {
+ if (entry.target === chartElement) {
+ setContainerWidth(entry.contentRect.width);
+ }
+ }
+ });
+
+ resizeObserver.observe(chartElement);
+
+ return () => {
+ resizeObserver.disconnect();
+ };
+ }, []);
+
+ useEffect(() => {
+ setIsSideBarTooltipOpen(false);
+ setIsLegendExpanded(false);
+ }, [datasets]);
+
+ const legendItems: LegendItem[] = useMemo(() => {
+ return getLegendItems(datasets, colors);
+ }, [datasets, colors]);
+
+ const id = useId();
+
+ const xAxis = useMemo(() => {
+ return (
+ <div className="crayon-scatter-chart-x-axis-container-outer" ref={xAxisContainerRef}>
+ <div
+ className="crayon-scatter-chart-x-axis-container"
+ style={
+ containerWidth
+ ? {
+ width: containerWidth - yAxisWidth,
+ marginLeft: yAxisWidth,
+ }
+ : {
+ width: "90%",
+ }
+ }
+ >
+ {/* X-axis only chart - synchronized with main chart */}
+ <ChartContainer
+ config={chartConfig}
+ style={{ width: "100%", height: X_AXIS_HEIGHT }}
+ rechartsProps={{
+ height: X_AXIS_HEIGHT,
+ }}
+ >
+ <RechartsScatterChart
+ key={`x-axis-scatter-chart-${id}`}
+ data={transformedData}
+ margin={{
+ top: 10,
+ bottom: 0,
+ left: DEFAULT_MARGIN - 3,
+ right: 2,
+ }}
+ >
+ <XAxis
+ type="number"
+ height={X_AXIS_HEIGHT}
+ name={xAxisLabel as string}
+ tickLine={false}
+ axisLine={false}
+ tickFormatter={numberTickFormatter}
+ tick={{ fontSize: 12 }}
+ domain={xDomain}
+ dataKey={xAxisDataKey}
+ />
+ {/* Invisible scatter to maintain scale synchronization */}
+ <Scatter
+ data={transformedData}
+ fill="transparent"
+ isAnimationActive={isAnimationActive}
+ shape="circle"
+ />
+ </RechartsScatterChart>
+ </ChartContainer>
+ </div>
+ </div>
+ );
+ }, [
+ chartConfig,
+ transformedData,
+ id,
+ yAxisWidth,
+ xDomain,
+ xAxisDataKey,
+ isAnimationActive,
+ containerWidth,
+ xAxisLabel,
+ ]);
+
+ return (
+ <SideBarTooltipProvider
+ isSideBarTooltipOpen={isSideBarTooltipOpen}
+ setIsSideBarTooltipOpen={setIsSideBarTooltipOpen}
+ data={sideBarTooltipData}
+ setData={setSideBarTooltipData}
+ >
+ <div
+ className={clsx("crayon-scatter-chart-container", className)}
+ style={{
+ width: typeof width === "number" ? `${width}px` : width || "100%",
+ height: isFixedNumericHeight ? "auto" : height || "100%",
+ }}
+ ref={chartWrapperRef}
+ >
+ <div className="crayon-scatter-chart-container-inner">
+ <div
+ className="crayon-scatter-chart-main-container"
+ style={{
+ width: "100%",
+ height: typeof height === "number" ? `${height}px` : height || DEFAULT_CHART_HEIGHT,
+ }}
+ >
+ <ChartContainer
+ config={chartConfig}
+ style={{
+ width: "100%",
+ height: "100%",
+ aspectRatio: 0,
+ }}
+ rechartsProps={{
+ width: "100%",
+ height: "100%",
+ }}
+ >
+ <RechartsScatterChart
+ key={`scatter-chart-${id}`}
+ margin={{
+ bottom: 10,
+ }}
+ >
+ {grid && gridCartesianGrid({ horizontal: true, vertical: true })}
+ <XAxis
+ type="number"
+ height={X_AXIS_HEIGHT}
+ name={xAxisLabel as string}
+ tickLine={false}
+ axisLine={false}
+ tickFormatter={numberTickFormatter}
+ tick={{ fontSize: 12 }}
+ domain={xDomain}
+ dataKey={xAxisDataKey}
+ hide
+ />
+
+ <YAxis
+ type="number"
+ dataKey={yAxisDataKey}
+ name={yAxisLabel as string}
+ domain={yDomain}
+ tickLine={false}
+ axisLine={false}
+ tick={<YAxisTick setLabelWidth={setLabelWidth} />}
+ tickFormatter={numberTickFormatter}
+ />
+
+ <ChartTooltip
+ content={<CustomTooltipContent parentRef={chartWrapperRef} hideIndicator />}
+ offset={15}
+ />
+
+ <Scatter
+ key={`scatter-${id}`}
+ data={transformedData}
+ shape={renderDotShape}
+ activeShape={renderActiveDotShape}
+ isAnimationActive={isAnimationActive}
+ >
+ {transformedData.map((entry, index) => (
+ <Cell key={`cell-${index}`} fill={entry["color"] as string} />
+ ))}
+ </Scatter>
+ </RechartsScatterChart>
+ </ChartContainer>
+ </div>
+
+ {isSideBarTooltipOpen && chartHeight > 0 && <SideBarTooltip height={chartHeight} />}
+ </div>
+ {xAxis}
+ <div className="crayon-scatter-chart-legend-container" ref={legendContainerRef}>
+ {legend && (
+ <DefaultLegend
+ items={legendItems}
+ yAxisLabel={yAxisLabel}
+ xAxisLabel={xAxisLabel}
+ containerWidth={containerWidth}
+ isExpanded={isLegendExpanded}
+ setIsExpanded={setIsLegendExpanded}
+ />
+ )}
+ </div>
+ </div>
+ </SideBarTooltipProvider>
+ );
+};
diff --git a/js/packages/react-ui/src/components/Charts/ScatterChart/components/ScatterDot.tsx b/js/packages/react-ui/src/components/Charts/ScatterChart/components/ScatterDot.tsx
new file mode 100644
index 000000000..a8e3d8300
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/ScatterChart/components/ScatterDot.tsx
@@ -0,0 +1,58 @@
+import React from "react";
+
+export interface ScatterDotProps {
+ cx?: number;
+ cy?: number;
+ fill?: string;
+ radius?: number;
+ variant?: "circle" | "square";
+ active?: boolean;
+}
+
+const ScatterDot: React.FC<ScatterDotProps> = ({
+ cx,
+ cy,
+ fill,
+ variant = "circle",
+ active = false,
+}) => {
+ if (typeof cx !== "number" || typeof cy !== "number") {
+ return null;
+ }
+
+ const OUTLINE_COLOR = "var(--crayon-sunk-fills)";
+ const OUTLINE_WIDTH = 2;
+ const displayRadius = active ? 5 : 3;
+
+ if (variant === "square") {
+ const sideLength = displayRadius * 2;
+ return (
+ <rect
+ x={cx - displayRadius}
+ y={cy - displayRadius}
+ width={sideLength}
+ height={sideLength}
+ fill={fill}
+ stroke={active ? OUTLINE_COLOR : "none"}
+ strokeWidth={OUTLINE_WIDTH}
+ strokeLinejoin="round"
+ vectorEffect="non-scaling-stroke"
+ rx={2}
+ />
+ );
+ }
+
+ return (
+ <circle
+ cx={cx}
+ cy={cy}
+ r={displayRadius}
+ fill={fill}
+ stroke={active ? OUTLINE_COLOR : "none"}
+ strokeWidth={OUTLINE_WIDTH}
+ vectorEffect="non-scaling-stroke"
+ />
+ );
+};
+
+export default ScatterDot;
diff --git a/js/packages/react-ui/src/components/Charts/ScatterChart/index.ts b/js/packages/react-ui/src/components/Charts/ScatterChart/index.ts
new file mode 100644
index 000000000..055cba60e
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/ScatterChart/index.ts
@@ -0,0 +1,4 @@
+export { ScatterChart } from "./ScatterChart";
+export type { ScatterChartProps } from "./ScatterChart";
+export type * from "./types";
+export * from "./utils/ScatterChartUtils";
diff --git a/js/packages/react-ui/src/components/Charts/ScatterChart/scatterChart.scss b/js/packages/react-ui/src/components/Charts/ScatterChart/scatterChart.scss
new file mode 100644
index 000000000..a1df6173e
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/ScatterChart/scatterChart.scss
@@ -0,0 +1,46 @@
+@use "../../../cssUtils" as cssUtils;
+
+.crayon-scatter-chart-container {
+ position: relative;
+ width: 100%;
+ height: auto;
+ display: flex;
+ flex-direction: column;
+}
+.crayon-scatter-chart-container-inner {
+ position: relative;
+ display: flex;
+ width: 100%;
+ flex: 1 1 auto;
+ min-width: 0;
+}
+.crayon-scatter-chart-x-axis-container-outer {
+ width: 100%;
+ display: flex;
+ justify-content: flex-end;
+ border-bottom: 1px solid cssUtils.$stroke-default;
+ box-sizing: border-box;
+}
+.crayon-scatter-chart-x-axis-container {
+ flex-shrink: 0;
+ width: 100%;
+ padding-top: cssUtils.$spacing-2xs;
+}
+.crayon-scatter-chart-y-axis-container {
+ flex-shrink: 0;
+}
+
+.crayon-scatter-chart-main-container {
+ width: 100%;
+ overflow-x: auto;
+ /* Hide scrollbar for Chrome, Safari and Opera */
+ &::-webkit-scrollbar {
+ display: none;
+ }
+
+ /* Hide scrollbar for Firefox */
+ scrollbar-width: none;
+
+ /* Hide scrollbar for IE and Edge */
+ -ms-overflow-style: none;
+}
diff --git a/js/packages/react-ui/src/components/Charts/ScatterChart/stories/ScatterChart.stories.tsx b/js/packages/react-ui/src/components/Charts/ScatterChart/stories/ScatterChart.stories.tsx
new file mode 100644
index 000000000..364a1b179
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/ScatterChart/stories/ScatterChart.stories.tsx
@@ -0,0 +1,820 @@
+import type { Meta, StoryObj } from "@storybook/react";
+import {
+ Calendar,
+ Globe,
+ Laptop,
+ Monitor,
+ Smartphone,
+ TabletSmartphone,
+ Tv,
+ Watch,
+} from "lucide-react";
+import { useState } from "react";
+import { Card } from "../../../Card";
+import { ScatterChart, ScatterChartProps } from "../ScatterChart";
+
+const customColorPalette = [
+ "#0A0E60",
+ "#14197B",
+ "#272DA6",
+ "#383FC9",
+ "#444CE7",
+ "#5F67F4",
+ "#7884FF",
+ "#97A9FF",
+ "#B4C6FF",
+ "#CBD7FF",
+];
+
+// Sample scatter chart datasets
+const dataVariations = {
+ default: [
+ {
+ name: "A school",
+ data: [
+ { x: 100, y: 200, z: 200 },
+ { x: 120, y: 100, z: 260 },
+ { x: 170, y: 300, z: 400 },
+ { x: 140, y: 250, z: 280 },
+ { x: 150, y: 400, z: 500 },
+ { x: 110, y: 280, z: 200 },
+ ],
+ },
+ {
+ name: "B school",
+ data: [
+ { x: 200, y: 180, z: 240 },
+ { x: 180, y: 350, z: 220 },
+ { x: 160, y: 320, z: 250 },
+ { x: 190, y: 150, z: 210 },
+ ],
+ },
+ ],
+ correlation: [
+ {
+ name: "Revenue",
+ data: [
+ { x: 1000, y: 1200 },
+ { x: 1200, y: 1400 },
+ { x: 1700, y: 2100 },
+ { x: 1400, y: 1800 },
+ { x: 1500, y: 1950 },
+ { x: 1100, y: 1300 },
+ { x: 2000, y: 2500 },
+ { x: 1800, y: 2200 },
+ { x: 1600, y: 1850 },
+ { x: 1900, y: 2350 },
+ { x: 1300, y: 1600 },
+ { x: 2200, y: 2800 },
+ ],
+ },
+ {
+ name: "Profit",
+ data: [
+ { x: 1000, y: 200 },
+ { x: 1200, y: 280 },
+ { x: 1700, y: 420 },
+ { x: 1400, y: 350 },
+ { x: 1500, y: 380 },
+ { x: 1100, y: 240 },
+ { x: 2000, y: 500 },
+ { x: 1800, y: 450 },
+ { x: 1600, y: 390 },
+ { x: 1900, y: 470 },
+ { x: 1300, y: 320 },
+ { x: 2200, y: 580 },
+ ],
+ },
+ ],
+ multipleDatasets: [
+ {
+ name: "Desktop",
+ data: [
+ { x: 1, y: 4 },
+ { x: 2, y: 2 },
+ { x: 3, y: 7 },
+ { x: 4, y: 5 },
+ { x: 5, y: 8 },
+ { x: 6, y: 3 },
+ { x: 7, y: 9 },
+ { x: 8, y: 6 },
+ { x: 9, y: 10 },
+ { x: 10, y: 1 },
+ ],
+ },
+ {
+ name: "Mobile",
+ data: [
+ { x: 1, y: 3 },
+ { x: 2, y: 5 },
+ { x: 3, y: 4 },
+ { x: 4, y: 7 },
+ { x: 5, y: 6 },
+ { x: 6, y: 8 },
+ { x: 7, y: 5 },
+ { x: 8, y: 9 },
+ { x: 9, y: 7 },
+ { x: 10, y: 8 },
+ ],
+ },
+ {
+ name: "Tablet",
+ data: [
+ { x: 1, y: 2 },
+ { x: 2, y: 6 },
+ { x: 3, y: 3 },
+ { x: 4, y: 4 },
+ { x: 5, y: 7 },
+ { x: 6, y: 5 },
+ { x: 7, y: 6 },
+ { x: 8, y: 8 },
+ { x: 9, y: 4 },
+ { x: 10, y: 9 },
+ ],
+ },
+ ],
+ performance: [
+ {
+ name: "Performance",
+ data: [
+ { x: 30, y: 1200 },
+ { x: 35, y: 1500 },
+ { x: 40, y: 1800 },
+ { x: 45, y: 2100 },
+ { x: 50, y: 2400 },
+ { x: 55, y: 2700 },
+ { x: 60, y: 3000 },
+ { x: 25, y: 900 },
+ { x: 65, y: 3300 },
+ { x: 70, y: 3600 },
+ ],
+ },
+ {
+ name: "Efficiency",
+ data: [
+ { x: 30, y: 1100 },
+ { x: 35, y: 1350 },
+ { x: 40, y: 1650 },
+ { x: 45, y: 1950 },
+ { x: 50, y: 2200 },
+ { x: 55, y: 2500 },
+ { x: 60, y: 2850 },
+ { x: 25, y: 800 },
+ { x: 65, y: 3150 },
+ { x: 70, y: 3450 },
+ ],
+ },
+ ],
+ comprehensive: [
+ {
+ name: "North America Sales",
+ data: [
+ { x: 1200, y: 8500, z: 120 },
+ { x: 1350, y: 9200, z: 140 },
+ { x: 1100, y: 7800, z: 95 },
+ { x: 1450, y: 10200, z: 160 },
+ { x: 1250, y: 8900, z: 130 },
+ { x: 1600, y: 11500, z: 180 },
+ { x: 1050, y: 7600, z: 85 },
+ { x: 1700, y: 12800, z: 200 },
+ { x: 1300, y: 9100, z: 135 },
+ { x: 1500, y: 10800, z: 170 },
+ { x: 1150, y: 8200, z: 110 },
+ { x: 1750, y: 13200, z: 210 },
+ { x: 1400, y: 9800, z: 150 },
+ { x: 1650, y: 12100, z: 190 },
+ { x: 1220, y: 8700, z: 125 },
+ { x: 1800, y: 13800, z: 220 },
+ { x: 1180, y: 8100, z: 105 },
+ { x: 1550, y: 11100, z: 175 },
+ { x: 1280, y: 9000, z: 128 },
+ { x: 1620, y: 11800, z: 185 },
+ { x: 1120, y: 7900, z: 100 },
+ { x: 1720, y: 13000, z: 205 },
+ { x: 1380, y: 9500, z: 145 },
+ { x: 1680, y: 12500, z: 195 },
+ { x: 1240, y: 8800, z: 120 },
+ ],
+ },
+ {
+ name: "Europe Sales",
+ data: [
+ { x: 980, y: 7200, z: 88 },
+ { x: 1150, y: 8400, z: 115 },
+ { x: 1020, y: 7500, z: 95 },
+ { x: 1280, y: 9200, z: 140 },
+ { x: 1080, y: 7800, z: 105 },
+ { x: 1420, y: 10100, z: 165 },
+ { x: 950, y: 6900, z: 80 },
+ { x: 1520, y: 11200, z: 185 },
+ { x: 1120, y: 8200, z: 120 },
+ { x: 1380, y: 9800, z: 155 },
+ { x: 1050, y: 7600, z: 100 },
+ { x: 1580, y: 11800, z: 195 },
+ { x: 1180, y: 8600, z: 130 },
+ { x: 1480, y: 10700, z: 175 },
+ { x: 1000, y: 7300, z: 90 },
+ { x: 1620, y: 12200, z: 205 },
+ { x: 1060, y: 7700, z: 102 },
+ { x: 1320, y: 9400, z: 145 },
+ { x: 1100, y: 8000, z: 115 },
+ { x: 1450, y: 10400, z: 170 },
+ { x: 970, y: 7100, z: 85 },
+ { x: 1550, y: 11500, z: 190 },
+ { x: 1140, y: 8300, z: 125 },
+ { x: 1680, y: 12600, z: 200 },
+ { x: 1040, y: 7500, z: 98 },
+ ],
+ },
+ {
+ name: "Asia Pacific Sales",
+ data: [
+ { x: 1800, y: 15200, z: 280 },
+ { x: 1950, y: 16800, z: 320 },
+ { x: 1650, y: 13800, z: 240 },
+ { x: 2100, y: 18200, z: 360 },
+ { x: 1750, y: 14800, z: 260 },
+ { x: 2250, y: 19500, z: 400 },
+ { x: 1600, y: 13200, z: 220 },
+ { x: 2350, y: 20200, z: 420 },
+ { x: 1900, y: 16200, z: 300 },
+ { x: 2150, y: 18500, z: 380 },
+ { x: 1700, y: 14200, z: 250 },
+ { x: 2400, y: 20800, z: 440 },
+ { x: 2000, y: 17200, z: 340 },
+ { x: 2200, y: 18800, z: 390 },
+ { x: 1820, y: 15500, z: 290 },
+ { x: 2450, y: 21200, z: 460 },
+ { x: 1720, y: 14500, z: 255 },
+ { x: 2050, y: 17500, z: 350 },
+ { x: 1870, y: 15800, z: 295 },
+ { x: 2300, y: 19800, z: 410 },
+ { x: 1780, y: 15000, z: 275 },
+ { x: 2500, y: 21800, z: 480 },
+ { x: 1920, y: 16400, z: 310 },
+ { x: 2070, y: 17700, z: 355 },
+ { x: 1830, y: 15600, z: 285 },
+ ],
+ },
+ {
+ name: "Latin America Sales",
+ data: [
+ { x: 650, y: 4200, z: 55 },
+ { x: 780, y: 5100, z: 75 },
+ { x: 720, y: 4800, z: 65 },
+ { x: 850, y: 5800, z: 90 },
+ { x: 690, y: 4500, z: 60 },
+ { x: 920, y: 6300, z: 105 },
+ { x: 620, y: 4000, z: 50 },
+ { x: 980, y: 6800, z: 120 },
+ { x: 750, y: 5000, z: 70 },
+ { x: 880, y: 6000, z: 95 },
+ { x: 670, y: 4400, z: 58 },
+ { x: 1020, y: 7100, z: 130 },
+ { x: 730, y: 4900, z: 68 },
+ { x: 950, y: 6500, z: 110 },
+ { x: 640, y: 4100, z: 52 },
+ { x: 1100, y: 7500, z: 150 },
+ { x: 700, y: 4700, z: 62 },
+ { x: 860, y: 5900, z: 92 },
+ { x: 680, y: 4600, z: 56 },
+ { x: 930, y: 6400, z: 108 },
+ { x: 610, y: 3900, z: 48 },
+ { x: 1050, y: 7200, z: 140 },
+ { x: 740, y: 4950, z: 69 },
+ { x: 970, y: 6650, z: 118 },
+ { x: 660, y: 4300, z: 54 },
+ ],
+ },
+ {
+ name: "Middle East & Africa",
+ data: [
+ { x: 450, y: 2800, z: 35 },
+ { x: 580, y: 3700, z: 55 },
+ { x: 520, y: 3300, z: 45 },
+ { x: 680, y: 4400, z: 70 },
+ { x: 490, y: 3100, z: 40 },
+ { x: 750, y: 4900, z: 85 },
+ { x: 420, y: 2600, z: 30 },
+ { x: 820, y: 5500, z: 100 },
+ { x: 560, y: 3600, z: 52 },
+ { x: 710, y: 4700, z: 78 },
+ { x: 470, y: 2900, z: 38 },
+ { x: 880, y: 5900, z: 115 },
+ { x: 530, y: 3400, z: 48 },
+ { x: 780, y: 5200, z: 92 },
+ { x: 440, y: 2700, z: 32 },
+ { x: 920, y: 6200, z: 125 },
+ { x: 500, y: 3200, z: 42 },
+ { x: 650, y: 4100, z: 65 },
+ { x: 480, y: 3000, z: 39 },
+ { x: 730, y: 4800, z: 80 },
+ { x: 410, y: 2500, z: 28 },
+ { x: 850, y: 5700, z: 105 },
+ { x: 540, y: 3500, z: 50 },
+ { x: 800, y: 5400, z: 95 },
+ { x: 460, y: 2850, z: 36 },
+ ],
+ },
+ {
+ name: "Small Business",
+ data: [
+ { x: 200, y: 1200, z: 15 },
+ { x: 280, y: 1600, z: 22 },
+ { x: 240, y: 1400, z: 18 },
+ { x: 320, y: 1900, z: 28 },
+ { x: 220, y: 1300, z: 16 },
+ { x: 360, y: 2200, z: 35 },
+ { x: 180, y: 1100, z: 12 },
+ { x: 400, y: 2500, z: 45 },
+ { x: 260, y: 1500, z: 20 },
+ { x: 340, y: 2100, z: 32 },
+ { x: 210, y: 1250, z: 15 },
+ { x: 380, y: 2400, z: 40 },
+ { x: 250, y: 1450, z: 19 },
+ { x: 370, y: 2300, z: 38 },
+ { x: 190, y: 1150, z: 13 },
+ { x: 420, y: 2700, z: 50 },
+ { x: 230, y: 1350, z: 17 },
+ { x: 290, y: 1700, z: 24 },
+ { x: 205, y: 1220, z: 15 },
+ { x: 350, y: 2150, z: 34 },
+ { x: 170, y: 1050, z: 11 },
+ { x: 390, y: 2450, z: 42 },
+ { x: 245, y: 1420, z: 18 },
+ { x: 375, y: 2350, z: 39 },
+ { x: 195, y: 1180, z: 14 },
+ ],
+ },
+ {
+ name: "Enterprise Clients",
+ data: [
+ { x: 2500, y: 35000, z: 800 },
+ { x: 2800, y: 38000, z: 900 },
+ { x: 2200, y: 32000, z: 700 },
+ { x: 3100, y: 42000, z: 1000 },
+ { x: 2650, y: 36500, z: 850 },
+ { x: 3400, y: 46000, z: 1200 },
+ { x: 2100, y: 30000, z: 650 },
+ { x: 3600, y: 48000, z: 1300 },
+ { x: 2750, y: 37500, z: 875 },
+ { x: 2950, y: 40000, z: 950 },
+ { x: 2350, y: 33500, z: 750 },
+ { x: 3750, y: 50000, z: 1400 },
+ { x: 2900, y: 39500, z: 925 },
+ { x: 3250, y: 44000, z: 1100 },
+ { x: 2550, y: 35500, z: 825 },
+ { x: 3850, y: 52000, z: 1500 },
+ { x: 2400, y: 34000, z: 775 },
+ { x: 3050, y: 41000, z: 975 },
+ { x: 2700, y: 37000, z: 860 },
+ { x: 3300, y: 45000, z: 1150 },
+ { x: 2250, y: 31500, z: 675 },
+ { x: 3500, y: 47000, z: 1250 },
+ { x: 2850, y: 38500, z: 910 },
+ { x: 3200, y: 43000, z: 1050 },
+ { x: 2600, y: 36000, z: 835 },
+ ],
+ },
+ {
+ name: "Government Contracts",
+ data: [
+ { x: 1800, y: 25000, z: 600 },
+ { x: 2100, y: 28000, z: 700 },
+ { x: 1650, y: 23000, z: 550 },
+ { x: 2400, y: 32000, z: 800 },
+ { x: 1950, y: 26500, z: 650 },
+ { x: 2700, y: 36000, z: 900 },
+ { x: 1500, y: 21000, z: 500 },
+ { x: 2850, y: 38000, z: 950 },
+ { x: 2250, y: 30000, z: 750 },
+ { x: 2550, y: 34000, z: 850 },
+ { x: 1750, y: 24000, z: 575 },
+ { x: 3000, y: 40000, z: 1000 },
+ { x: 2150, y: 29000, z: 725 },
+ { x: 2600, y: 35000, z: 875 },
+ { x: 1850, y: 25500, z: 625 },
+ { x: 3100, y: 41000, z: 1025 },
+ { x: 1700, y: 23500, z: 525 },
+ { x: 2300, y: 30500, z: 775 },
+ { x: 2000, y: 27500, z: 675 },
+ { x: 2750, y: 37000, z: 925 },
+ { x: 1600, y: 22500, z: 525 },
+ { x: 2900, y: 39000, z: 975 },
+ { x: 2200, y: 29500, z: 740 },
+ { x: 2650, y: 35500, z: 890 },
+ { x: 1900, y: 26000, z: 640 },
+ ],
+ },
+ ],
+};
+
+const icons = {
+ desktop: Monitor,
+ mobile: TabletSmartphone,
+ tablet: Calendar,
+ series1: Globe,
+ series2: Smartphone,
+ revenue: Laptop,
+ profit: Tv,
+ performance: Watch,
+ efficiency: Monitor,
+} as const;
+
+/**
+ * # ScatterChart Component Documentation
+ *
+ * The ScatterChart component is designed for visualizing relationships between two continuous variables.
+ * It's ideal for:
+ *
+ * - **Correlation Analysis**: Identifying relationships between variables.
+ * - **Distribution Analysis**: Understanding data point clustering and outliers.
+ * - **Comparative Analysis**: Comparing multiple datasets on the same coordinate system.
+ *
+ * ## Key Features
+ *
+ * ### Interactive & Responsive
+ * - **Interactive Tooltips**: Hover over points to see detailed data values.
+ * - **Multiple Datasets**: Support for multiple data series with different colors.
+ * - **Responsive Design**: Adapts to any container size.
+ *
+ * ### Customization
+ * - **Theming**: Six pre-built color palettes or custom colors.
+ * - **Shape Options**: Multiple point shapes (circle, diamond, square, etc.).
+ * - **Axis Configuration**: Customizable axis labels, units, and domains.
+ */
+const meta: Meta<ScatterChartProps> = {
+ title: "Components/Charts/ScatterChart",
+ component: ScatterChart,
+ parameters: {
+ layout: "centered",
+ docs: {
+ description: {
+ component: `
+## Installation and Basic Usage
+
+\`\`\`tsx
+import { ScatterChart } from '@crayon-ui/react-ui/Charts/ScatterChart';
+
+const scatterData = [
+ { x: 100, y: 200, category: "A" },
+ { x: 120, y: 100, category: "B" },
+ { x: 170, y: 300, category: "A" },
+];
+
+// Basic implementation
+<ScatterChart
+ data={scatterData}
+ xAxisDataKey="x"
+ yAxisDataKey="y"
+ theme="ocean"
+/>
+
+// With custom labels and units
+<ScatterChart
+ data={scatterData}
+ xAxisDataKey="x"
+ yAxisDataKey="y"
+ xAxisLabel="Temperature (°C)"
+ yAxisLabel="Sales ($)"
+ xAxisUnit="°C"
+ yAxisUnit="$"
+/>
+\`\`\`
+
+## Data Structure Requirements
+
+Your data should be an array of objects. Each object must contain:
+- **x coordinate** (number): The X-axis value for the point.
+- **y coordinate** (number): The Y-axis value for the point.
+- One or more **series fields**: Additional fields that define different datasets/series.
+
+\`\`\`tsx
+const scatterData = [
+ { x: 10, y: 20, dataset1: 1, dataset2: 1 },
+ { x: 15, y: 25, dataset1: 1, dataset2: 1 },
+ { x: 20, y: 30, dataset1: 1, dataset2: 1 },
+];
+\`\`\`
+`,
+ },
+ },
+ },
+ tags: ["!dev", "autodocs"],
+ argTypes: {
+ data: {
+ description: `
+**Required.** An array of data objects for the scatter chart. Each object should contain:
+- x coordinate (number) for the X-axis.
+- y coordinate (number) for the Y-axis.
+- One or more series identifiers.
+`,
+ control: false,
+ table: {
+ type: { summary: "Array<Record<string, string | number>>" },
+ category: "📊 Data Configuration",
+ },
+ },
+ xAxisDataKey: {
+ description: "The key in your data object that represents the X-axis values.",
+ control: "text",
+ table: {
+ defaultValue: { summary: "x" },
+ category: "📊 Data Configuration",
+ },
+ },
+ yAxisDataKey: {
+ description: "The key in your data object that represents the Y-axis values.",
+ control: "text",
+ table: {
+ defaultValue: { summary: "y" },
+ category: "📊 Data Configuration",
+ },
+ },
+ theme: {
+ description: "Specifies the color palette for the chart points and legend.",
+ control: "select",
+ options: ["ocean", "orchid", "emerald", "sunset", "spectrum", "vivid"],
+ table: {
+ defaultValue: { summary: "ocean" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ customPalette: {
+ description: "Custom array of colors to use instead of the theme palette.",
+ control: "object",
+ table: {
+ type: { summary: "string[]" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ shape: {
+ description: "The shape of the scatter points.",
+ control: "select",
+ options: ["circle", "square"],
+ table: {
+ defaultValue: { summary: "circle" },
+ category: "🎨 Visual Styling",
+ },
+ },
+ grid: {
+ description: "Toggles the visibility of the background grid lines.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ legend: {
+ description: "Toggles the visibility of the chart legend.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "true" },
+ category: "📱 Display Options",
+ },
+ },
+ isAnimationActive: {
+ description: "Enables or disables the initial loading animation.",
+ control: "boolean",
+ table: {
+ defaultValue: { summary: "false" },
+ category: "🎬 Animation & Interaction",
+ },
+ },
+ xAxisLabel: {
+ description: "A label to display below the X-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ yAxisLabel: {
+ description: "A label to display beside the Y-axis.",
+ control: "text",
+ table: {
+ type: { summary: "React.ReactNode" },
+ category: "📱 Display Options",
+ },
+ },
+ className: {
+ description: "Custom CSS class to apply to the chart's container.",
+ control: "text",
+ table: {
+ type: { summary: "string" },
+ category: "Layout & Sizing",
+ },
+ },
+ height: {
+ description: "Sets the height of the chart container.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ width: {
+ description: "Sets the width of the chart container.",
+ control: "number",
+ table: {
+ type: { summary: "number" },
+ category: "Layout & Sizing",
+ },
+ },
+ },
+} satisfies Meta<typeof ScatterChart>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/**
+ * ## Basic Scatter Chart
+ *
+ * This demonstrates a basic scatter chart with default settings.
+ * Perfect for showing simple correlations between two variables.
+ */
+export const BasicScatter: Story = {
+ name: "📈 Basic Scatter Chart",
+ args: {
+ data: dataVariations.default,
+ xAxisDataKey: "x",
+ yAxisDataKey: "y",
+ theme: "ocean",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ showYAxis: true,
+ showXAxis: true,
+ shape: "circle",
+ width: 700,
+ height: 400,
+ },
+ render: (args: any) => <ScatterChart {...args} />,
+};
+
+/**
+ * ## Correlation Analysis
+ *
+ * This example shows how to use the scatter chart for correlation analysis.
+ * Notice how the points follow a general upward trend, indicating positive correlation.
+ */
+export const CorrelationAnalysis: Story = {
+ name: "📊 Correlation Analysis",
+ args: {
+ data: dataVariations.correlation,
+ xAxisDataKey: "x",
+ yAxisDataKey: "y",
+ theme: "emerald",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ xAxisLabel: "Marketing Spend",
+ yAxisLabel: "Sales Revenue",
+ shape: "circle",
+ },
+ render: (args: any) => (
+ <Card style={{ width: "700px" }}>
+ <ScatterChart {...args} />
+ </Card>
+ ),
+};
+
+/**
+ * ## Shape Comparison
+ *
+ * Compare different point shapes available in the scatter chart.
+ * Each shape provides a different visual style for your data points.
+ */
+export const ShapeComparison: Story = {
+ name: "🔷 Shape Comparison",
+ args: {
+ data: dataVariations.default as never,
+ xAxisDataKey: "x",
+ yAxisDataKey: "y",
+ theme: "sunset",
+ grid: true,
+ legend: true,
+ isAnimationActive: false,
+ },
+ render: (args: any) => {
+ const shapes = ["circle", "square"] as const;
+
+ return (
+ <div style={{ display: "flex", flexDirection: "column", gap: "20px" }}>
+ {shapes.map((shape) => (
+ <div key={shape}>
+ <h4
+ style={{
+ margin: "0 0 8px 0",
+ fontSize: "14px",
+ fontWeight: "600",
+ textTransform: "capitalize",
+ }}
+ >
+ {shape} Shape
+ </h4>
+ <Card style={{ width: "500px" }}>
+ <ScatterChart {...args} shape={shape} />
+ </Card>
+ </div>
+ ))}
+ </div>
+ );
+ },
+};
+
+/**
+ * ## Data Explorer
+ *
+ * Interactive tool for exploring different scatter chart datasets.
+ * Use the buttons to switch between various data scenarios.
+ */
+export const DataExplorer: Story = {
+ name: "🎛️ Data Explorer",
+ args: {
+ data: dataVariations.default as never,
+ xAxisDataKey: "x",
+ yAxisDataKey: "y",
+ theme: "ocean",
+ grid: true,
+ legend: true,
+ isAnimationActive: true,
+ shape: "circle",
+ },
+ render: (args: any) => {
+ const [selectedDataType, setSelectedDataType] =
+ useState<keyof typeof dataVariations>("default");
+
+ const currentData = dataVariations[selectedDataType];
+
+ const buttonStyle = {
+ margin: "2px",
+ padding: "6px 12px",
+ fontSize: "12px",
+ border: "1px solid #ddd",
+ borderRadius: "4px",
+ cursor: "pointer",
+ background: "#fff",
+ fontFamily: "monospace",
+ };
+
+ const activeButtonStyle = {
+ ...buttonStyle,
+ background: "#007acc",
+ color: "white",
+ border: "1px solid #007acc",
+ };
+
+ return (
+ <div>
+ <div
+ style={{
+ marginBottom: "16px",
+ padding: "12px",
+ background: "#f8f9fa",
+ borderRadius: "8px",
+ border: "1px solid #e9ecef",
+ width: "600px",
+ }}
+ >
+ <strong>📈 Scatter Chart Test Suite:</strong>
+ <div style={{ marginTop: "8px", display: "flex", flexWrap: "wrap", gap: "4px" }}>
+ <button
+ onClick={() => setSelectedDataType("default")}
+ style={selectedDataType === "default" ? activeButtonStyle : buttonStyle}
+ >
+ 📊 Default
+ </button>
+ <button
+ onClick={() => setSelectedDataType("correlation")}
+ style={selectedDataType === "correlation" ? activeButtonStyle : buttonStyle}
+ >
+ 📈 Correlation
+ </button>
+ <button
+ onClick={() => setSelectedDataType("multipleDatasets")}
+ style={selectedDataType === "multipleDatasets" ? activeButtonStyle : buttonStyle}
+ >
+ 🎯 Multiple Datasets
+ </button>
+ <button
+ onClick={() => setSelectedDataType("performance")}
+ style={selectedDataType === "performance" ? activeButtonStyle : buttonStyle}
+ >
+ ⚡ Performance
+ </button>
+ <button
+ onClick={() => setSelectedDataType("comprehensive")}
+ style={selectedDataType === "comprehensive" ? activeButtonStyle : buttonStyle}
+ >
+ 🌍 Comprehensive
+ </button>
+ </div>
+ </div>
+ <Card style={{ width: "600px" }}>
+ <ScatterChart {...args} data={currentData} height="600px" />
+ </Card>
+ </div>
+ );
+ },
+};
diff --git a/js/packages/react-ui/src/components/Charts/ScatterChart/types/index.ts b/js/packages/react-ui/src/components/Charts/ScatterChart/types/index.ts
new file mode 100644
index 000000000..025a36ea7
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/ScatterChart/types/index.ts
@@ -0,0 +1,13 @@
+export interface ScatterPoint {
+ x: number;
+ y: number;
+ z?: number;
+ [key: string]: string | number | undefined;
+}
+
+export interface ScatterDataset {
+ name: string;
+ data: ScatterPoint[];
+}
+
+export type ScatterChartData = ScatterDataset[];
diff --git a/js/packages/react-ui/src/components/Charts/ScatterChart/utils/ScatterChartUtils.ts b/js/packages/react-ui/src/components/Charts/ScatterChart/utils/ScatterChartUtils.ts
new file mode 100644
index 000000000..d5f89fb7d
--- /dev/null
+++ b/js/packages/react-ui/src/components/Charts/ScatterChart/utils/ScatterChartUtils.ts
@@ -0,0 +1,94 @@
+import { ScatterChartData, ScatterPoint } from "../types";
+
+/**
+ * Extracts dataset names from scatter chart data
+ * @param data - The scatter chart data (array of datasets)
+ * @returns Array of dataset names
+ */
+export const getScatterDatasets = (data: ScatterChartData): string[] => {
+ if (!data || !Array.isArray(data)) {
+ return [];
+ }
+ return data.map((dataset) => dataset.name);
+};
+
+/**
+ * Transforms scatter chart data for recharts consumption
+ * @param data - The scatter chart data (array of datasets)
+ * @param datasets - Array of dataset names to include
+ * @param colors - Array of colors for datasets
+ * @returns Flattened array of all points with color and dataset info
+ */
+export const transformScatterData = (
+ data: ScatterChartData,
+ datasets: string[],
+ colors: string[],
+) => {
+ // Guard against undefined or null data
+ if (!data || !Array.isArray(data) || data.length === 0) {
+ return [];
+ }
+
+ const datasetColors: { [key: string]: string } = {};
+ datasets.forEach((ds, i) => {
+ datasetColors[ds] = colors[i] ?? "transparent";
+ });
+
+ // Flatten all datasets into a single array with dataset info
+ const transformedPoints: Array<ScatterPoint & { color: string; dataset: string }> = [];
+
+ data.forEach((dataset) => {
+ // Use only palette colors, ignore any hardcoded colors in datasets
+ const color = datasetColors[dataset.name] || "transparent";
+
+ dataset.data.forEach((point) => {
+ transformedPoints.push({
+ ...point,
+ x: Number(point.x),
+ y: Number(point.y),
+ z: point.z ? Number(point.z) : undefined,
+ color,
+ dataset: dataset.name,
+ });
+ });
+ });
+
+ return transformedPoints;
+};
+
+/**
+ * Calculates the domain for scatter chart axes
+ * @param data - The scatter chart data (array of datasets)
+ * @param axis - Which axis ('x' or 'y')
+ * @returns Domain array [min, max] with padding
+ */
+export const calculateScatterDomain = (
+ data: ScatterChartData,
+ axis: "x" | "y",
+): [number, number] => {
+ if (!data || !Array.isArray(data) || !data.length) return [0, 100];
+
+ // Flatten all data points from all datasets
+ const allPoints = data.flatMap((dataset) => dataset.data);
+
+ const values = allPoints.map((point) => Number(point[axis])).filter((val) => !isNaN(val));
+ if (!values.length) return [0, 100];
+
+ const min = Math.min(...values);
+ const max = Math.max(...values);
+ const padding = (max - min) * 0.1; // 10% padding
+
+ return [Math.max(0, min - padding), max + padding];
+};
+
+/**
+ * Formats scatter chart data for tooltip display
+ * @param dataKey - The data key being displayed
+ * @param value - The value to format
+ * @param unit - Optional unit to append
+ * @returns Formatted string
+ */
+export const formatScatterTooltipValue = (value: number | string, unit?: string): string => {
+ const formattedValue = typeof value === "number" ? value.toLocaleString() : value;
+ return unit ? `${formattedValue} ${unit}` : formattedValue;
+};
diff --git a/js/packages/react-ui/src/components/Charts/charts.scss b/js/packages/react-ui/src/components/Charts/charts.scss
index faf37fbf9..7d546567b 100644
--- a/js/packages/react-ui/src/components/Charts/charts.scss
+++ b/js/packages/react-ui/src/components/Charts/charts.scss
@@ -10,6 +10,9 @@
// line chart css
@forward "./LineChart/lineChart.scss";
+// scatter chart css
+@forward "./ScatterChart/scatterChart.scss";
+
// radar chart css
@forward "./RadarChart/radarChart.scss";
@@ -77,10 +80,6 @@
stroke: cssUtils.$stroke-default;
}
-.crayon-chart-vertical-cartesian-grid {
- stroke: cssUtils.$stroke-default;
-}
-
.crayon-chart-polar-grid {
stroke: cssUtils.$stroke-default;
}
diff --git a/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx b/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx
index ce9140f6b..4fbc4b86b 100644
--- a/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx
+++ b/js/packages/react-ui/src/components/Charts/hooks/useYAxisLabelWidth.tsx
@@ -3,6 +3,7 @@ import { useCallback, useMemo, useRef, useState } from "react";
import { AreaChartData } from "../AreaChart";
import { BarChartData } from "../BarChart";
import { LineChartData } from "../LineChart";
+import { ScatterPoint } from "../ScatterChart/types";
import { numberTickFormatter } from "../utils";
import { useCanvasContextForLabelSize } from "./useCanvasContextForLabelSize";
@@ -12,7 +13,7 @@ const MAX_Y_AXIS_WIDTH = 200;
const LABEL_PADDING = 10;
export const useYAxisLabelWidth = (
- data: AreaChartData | LineChartData | BarChartData,
+ data: AreaChartData | LineChartData | BarChartData | ScatterPoint[],
dataKeys: string[],
) => {
const context = useCanvasContextForLabelSize();
@@ -38,7 +39,8 @@ export const useYAxisLabelWidth = (
values.forEach((value) => {
const displayValue = numberTickFormatter(value);
- const textWidth = context.measureText(displayValue).width;
+ const textWidth = context.measureText(displayValue + "123").width;
+
maxWidth = Math.max(maxWidth, textWidth);
});
});
diff --git a/js/packages/react-ui/src/components/Charts/index.ts b/js/packages/react-ui/src/components/Charts/index.ts
index 437f860ed..c9675066b 100644
--- a/js/packages/react-ui/src/components/Charts/index.ts
+++ b/js/packages/react-ui/src/components/Charts/index.ts
@@ -8,4 +8,5 @@ export * from "./MiniLineChart";
export * from "./PieChart";
export * from "./RadarChart";
export * from "./RadialChart";
+export * from "./ScatterChart";
export * from "./SegmentedBarChart";
diff --git a/js/packages/react-ui/src/components/Charts/shared/CartesianGrid/cartesianGrid.tsx b/js/packages/react-ui/src/components/Charts/shared/CartesianGrid/cartesianGrid.tsx
index 492485311..8b2ff0416 100644
--- a/js/packages/react-ui/src/components/Charts/shared/CartesianGrid/cartesianGrid.tsx
+++ b/js/packages/react-ui/src/components/Charts/shared/CartesianGrid/cartesianGrid.tsx
@@ -1,22 +1,13 @@
import { CartesianGrid } from "recharts";
-export const cartesianGrid = () => (
- <CartesianGrid
- vertical={false}
- fillOpacity={1}
- strokeOpacity={1}
- strokeWidth={1}
- strokeDasharray="0"
- strokeLinecap="round"
- strokeLinejoin="round"
- stroke="currentColor"
- className="crayon-chart-cartesian-grid"
- />
-);
+export const cartesianGrid = () => gridCartesianGrid({ vertical: false });
+
+export const verticalCartesianGrid = () => gridCartesianGrid({ horizontal: false });
-export const verticalCartesianGrid = () => (
+export const gridCartesianGrid = (props: { vertical?: boolean; horizontal?: boolean }) => (
<CartesianGrid
- horizontal={false}
+ vertical={props.vertical ?? true}
+ horizontal={props.horizontal ?? true}
fillOpacity={1}
strokeOpacity={1}
strokeWidth={1}
@@ -24,6 +15,6 @@ export const verticalCartesianGrid = () => (
strokeLinecap="round"
strokeLinejoin="round"
stroke="currentColor"
- className="crayon-chart-vertical-cartesian-grid"
+ className="crayon-chart-cartesian-grid"
/>
);
diff --git a/js/packages/react-ui/src/components/Charts/utils/dataUtils.ts b/js/packages/react-ui/src/components/Charts/utils/dataUtils.ts
index b9d9b8d24..f704a1df2 100644
--- a/js/packages/react-ui/src/components/Charts/utils/dataUtils.ts
+++ b/js/packages/react-ui/src/components/Charts/utils/dataUtils.ts
@@ -84,13 +84,13 @@ export const getCategoricalChartConfig = <T extends CategoricalChartData>(
export const getLegendItems = (
dataKeys: string[],
colors: string[],
- icons: Partial<Record<string, React.ComponentType>>,
+ icons?: Partial<Record<string, React.ComponentType>>,
): LegendItem[] => {
return dataKeys.map((key, index) => ({
key,
label: key,
color: colors[index] ?? "#000000", // Fallback color if undefined
- icon: icons[key] as React.ComponentType | undefined,
+ icon: icons?.[key] as React.ComponentType | undefined,
}));
};
diff --git a/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts b/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts
index ed78eb035..13809901f 100644
--- a/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts
+++ b/js/packages/react-ui/src/components/Charts/utils/styleUtils.ts
@@ -17,6 +17,10 @@ const numberTickFormatter = (value: number) => {
} else if (absValue >= 1e3) {
return (value / 1e3).toFixed(absValue >= 10e3 ? 0 : 1) + "K";
} else {
+ // For values < 1000, show only 1 decimal place if there's a decimal
+ if (value % 1 !== 0) {
+ return value.toFixed(2);
+ }
return value.toString();
}
}