Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

refactor(web): Create design-system HistogramChart (#17833)

Ben Bachemf4d731a17369
diff --git a/web/src/components/design-system/charts/BarChart/BarChart.tsx b/web/src/components/design-system/charts/BarChart/BarChart.tsx
index 5f6011072c..f7d67a65d8 100644
--- a/web/src/components/design-system/charts/BarChart/BarChart.tsx
+++ b/web/src/components/design-system/charts/BarChart/BarChart.tsx
@@ -1,200 +1,13 @@
"use client";
-import { scaleBand, scaleLinear } from "d3-scale";
+import { type ComponentProps } from "react";
-import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
-import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
-import { CartesianLayout } from "@/src/components/design-system/internal/charts/CartesianLayout";
-import {
- ChartLegend,
- type ChartLegendItem,
-} from "@/src/components/design-system/internal/charts/ChartLegend";
-import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
+import { BarChartCore } from "@/src/components/design-system/internal/charts/BarChartCore";
-export type BarChartDatum = {
- label: string;
- value: number | null;
- color?: string;
-};
+export type { BarChartDatum } from "@/src/components/design-system/internal/charts/BarChartCore";
-type BarChartProps = {
- data: BarChartDatum[];
- valueFormatter?: (value: number) => string;
- color?: string;
- variant?: "default" | "subtle";
- hideXAxisLabels?: boolean;
- zeroBaseline?: boolean;
- ariaLabel?: string;
- legend?: { items: ChartLegendItem[] };
-};
+type BarChartProps = Omit<ComponentProps<typeof BarChartCore>, "barSpacing">;
-export function BarChart({
- data,
- valueFormatter = (value) => value.toLocaleString(),
- color = "hsl(var(--chart-1))",
- variant = "default",
- hideXAxisLabels = false,
- zeroBaseline = true,
- ariaLabel = "Bar chart",
- legend,
-}: BarChartProps) {
- const firstColor = data[0]?.color ?? color;
- const hasDistinctColors = data.some(
- (datum) => (datum.color ?? color) !== firstColor,
- );
-
- return (
- <div className="flex size-full min-w-0 flex-col">
- <div className="min-h-0 flex-1">
- <ChartContainer>
- {({ width, height }) => (
- <CartesianLayout
- width={width}
- height={height}
- showXAxisLabels={!hideXAxisLabels}
- >
- {({ measuredPlot, maxYTicks, plotForTicks }) => {
- const values = data.flatMap((datum) =>
- typeof datum.value === "number" &&
- Number.isFinite(datum.value)
- ? [datum.value]
- : [],
- );
- const min = values.length ? Math.min(...values) : 0;
- const max = values.length ? Math.max(...values) : 1;
- const domainMin = zeroBaseline ? Math.min(0, min) : min;
- const domainMax = Math.max(
- zeroBaseline || min < 0 ? 0 : min,
- max,
- );
- const domainPadding = Math.max(Math.abs(domainMin) * 0.1, 1);
- const plotHeight = measuredPlot.height;
- const yScale = scaleLinear()
- .domain(
- domainMin === domainMax
- ? [domainMin - domainPadding, domainMax + domainPadding]
- : [domainMin, domainMax],
- )
- .nice(maxYTicks)
- .range([measuredPlot.top + plotHeight, measuredPlot.top]);
- const yTicks = yScale.ticks(maxYTicks);
- const plot = plotForTicks(yTicks.map(valueFormatter));
- const leftMargin = plot.left;
- const plotWidth = plot.width;
- const xScale = scaleBand<number>()
- .domain(data.map((_, index) => index))
- .range([leftMargin, leftMargin + plotWidth])
- .paddingInner(0.2)
- .paddingOuter(0.1);
- const baseline = yScale(
- zeroBaseline || min < 0 ? 0 : (yScale.domain()[0] ?? 0),
- );
- const xTicks = data.map((datum, index) => ({
- key: String(index),
- x: (xScale(index) ?? leftMargin) + xScale.bandwidth() / 2,
- label: datum.label,
- maxWidth: xScale.bandwidth() - 8,
- }));
-
- if (
- width <= 0 ||
- height <= 0 ||
- plotWidth <= 0 ||
- plotHeight <= 0
- ) {
- return (
- <svg width={width} height={height} aria-hidden="true" />
- );
- }
-
- return (
- <ChartTooltip>
- {({ activeIndex, getReferenceProps }) => (
- <CartesianChart
- width={width}
- height={height}
- ariaLabel={ariaLabel}
- overflow="hidden"
- plot={plot}
- yTicks={yTicks}
- y={yScale}
- valueFormatter={valueFormatter}
- zeroY={min < 0 ? yScale(0) : undefined}
- xAxis={
- hideXAxisLabels
- ? undefined
- : {
- ticks: xTicks,
- activeKey:
- activeIndex === undefined
- ? undefined
- : String(activeIndex),
- showCategoryTicks: true,
- alignment: "center",
- }
- }
- >
- {data.map((datum, index) => {
- const x = xScale(index);
- if (x === undefined) return null;
- const barColor = datum.color ?? color;
- const y =
- datum.value !== null && Number.isFinite(datum.value)
- ? yScale(datum.value)
- : baseline;
- const barTop = Math.min(y, baseline);
- const barHeight = Math.abs(y - baseline);
- const active = activeIndex === index;
- let colorStrength = 100;
- if (variant === "subtle") {
- colorStrength = active ? 60 : 30;
- }
- if (activeIndex !== undefined && !active) {
- colorStrength = variant === "subtle" ? 15 : 20;
- }
- const fill =
- colorStrength === 100
- ? barColor
- : `color-mix(in srgb, ${barColor} ${colorStrength}%, hsl(var(--background)))`;
- return (
- <g key={index}>
- {datum.value !== null &&
- Number.isFinite(datum.value) ? (
- <rect
- x={x}
- y={barTop}
- width={xScale.bandwidth()}
- height={Math.max(1, barHeight)}
- rx={Math.min(4, barHeight / 2)}
- fill={fill}
- role="graphics-symbol"
- tabIndex={0}
- aria-label={`${datum.label}: ${valueFormatter(datum.value)}`}
- className="outline-hidden transition-[fill] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2"
- {...getReferenceProps({
- type: "primary",
- index,
- label: datum.label,
- value: valueFormatter(datum.value),
- color: hasDistinctColors
- ? barColor
- : undefined,
- })}
- />
- ) : null}
- </g>
- );
- })}
- </CartesianChart>
- )}
- </ChartTooltip>
- );
- }}
- </CartesianLayout>
- )}
- </ChartContainer>
- </div>
- {legend?.items.length ? <ChartLegend items={legend.items} /> : null}
- </div>
- );
+export function BarChart(props: BarChartProps) {
+ return <BarChartCore {...props} barSpacing="default" />;
}
diff --git a/web/src/components/design-system/charts/HistogramChart/HistogramChart.stories.tsx b/web/src/components/design-system/charts/HistogramChart/HistogramChart.stories.tsx
new file mode 100644
index 0000000000..d123124e93
--- /dev/null
+++ b/web/src/components/design-system/charts/HistogramChart/HistogramChart.stories.tsx
@@ -0,0 +1,105 @@
+import preview from "../../../../../.storybook/preview";
+import { expect, within } from "storybook/test";
+
+import { HistogramChart } from "./HistogramChart";
+
+const data = [
+ { label: "[0, 10]", value: 12 },
+ { label: "[10, 20]", value: 24 },
+ { label: "[20, 30]", value: 18 },
+];
+
+const meta = preview.meta({
+ component: HistogramChart,
+ parameters: { layout: "fullscreen" },
+ args: { data },
+ decorators: [
+ (Story) => (
+ <div className="h-dvh w-full">
+ <Story />
+ </div>
+ ),
+ ],
+});
+
+export const Default = meta.story({});
+
+export const HistogramBinSpacing = meta.story({
+ name: "(Test) Histogram Bin Spacing",
+ play: async ({ canvasElement }) => {
+ const bars = within(canvasElement).getAllByRole("graphics-symbol");
+ const first = bars[0];
+ const second = bars[1];
+ if (!first || !second) throw new Error("Histogram bins not found");
+ await expect(first).toHaveAttribute("rx", "0");
+ await expect(
+ Number(first.getAttribute("x")) + Number(first.getAttribute("width")) + 2,
+ ).toBeCloseTo(Number(second.getAttribute("x")));
+ },
+});
+
+export const SubtleFill = meta.story({
+ args: { variant: "subtle" },
+});
+
+export const ManyBins = meta.story({
+ args: {
+ data: Array.from({ length: 20 }, (_, index) => ({
+ label: `[${index * 10}, ${(index + 1) * 10}]`,
+ value: 8 + index,
+ })),
+ },
+});
+
+const denseBins = Array.from({ length: 100 }, (_, index) => ({
+ label: `Bin ${index + 1}`,
+ value: index + 1,
+}));
+
+export const NarrowBins = meta.story({
+ name: "(Test) Narrow Bins Remain Visible",
+ args: { data: denseBins },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[240px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const bars = within(canvasElement).getAllByRole("graphics-symbol");
+ await expect(bars).toHaveLength(100);
+ for (const bar of bars) {
+ await expect(Number(bar.getAttribute("width"))).toBeGreaterThan(0);
+ }
+ },
+});
+
+export const InsufficientSpace = meta.story({
+ name: "(Test) Insufficient Space For Bins",
+ args: { data: denseBins },
+ decorators: [
+ (Story) => (
+ <div className="h-40 w-[100px]">
+ <Story />
+ </div>
+ ),
+ ],
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ await expect(canvas.getByText("Insufficient space")).toBeInTheDocument();
+ await expect(canvas.queryAllByRole("graphics-symbol")).toHaveLength(0);
+ },
+});
+
+export const NormalDistribution = meta.story({
+ args: {
+ data: Array.from({ length: 31 }, (_, index) => {
+ const x = (index - 15) / 3;
+ return {
+ label: `[${index - 15}, ${index - 14}]`,
+ value: 100 * Math.exp(-0.5 * x * x),
+ };
+ }),
+ },
+});
diff --git a/web/src/components/design-system/charts/HistogramChart/HistogramChart.tsx b/web/src/components/design-system/charts/HistogramChart/HistogramChart.tsx
new file mode 100644
index 0000000000..99ca25498b
--- /dev/null
+++ b/web/src/components/design-system/charts/HistogramChart/HistogramChart.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import { type ComponentProps } from "react";
+
+import { BarChartCore } from "@/src/components/design-system/internal/charts/BarChartCore";
+
+type HistogramChartProps = Omit<
+ ComponentProps<typeof BarChartCore>,
+ "barSpacing"
+>;
+
+export function HistogramChart(props: HistogramChartProps) {
+ return <BarChartCore {...props} barSpacing="histogram" />;
+}
diff --git a/web/src/components/design-system/internal/charts/BarChartCore.tsx b/web/src/components/design-system/internal/charts/BarChartCore.tsx
new file mode 100644
index 0000000000..4dd6daa5b8
--- /dev/null
+++ b/web/src/components/design-system/internal/charts/BarChartCore.tsx
@@ -0,0 +1,226 @@
+"use client";
+
+import { scaleBand, scaleLinear } from "d3-scale";
+
+import { ChartContainer } from "@/src/components/design-system/charts/ChartContainer";
+import { CartesianChart } from "@/src/components/design-system/internal/charts/CartesianChart";
+import { CartesianLayout } from "@/src/components/design-system/internal/charts/CartesianLayout";
+import {
+ ChartLegend,
+ type ChartLegendItem,
+} from "@/src/components/design-system/internal/charts/ChartLegend";
+import { ChartTooltip } from "@/src/components/design-system/internal/charts/ChartTooltip";
+
+export type BarChartDatum = {
+ label: string;
+ value: number | null;
+ color?: string;
+};
+
+type BarChartCoreProps = {
+ data: BarChartDatum[];
+ valueFormatter?: (value: number) => string;
+ color?: string;
+ variant?: "default" | "subtle";
+ hideXAxisLabels?: boolean;
+ zeroBaseline?: boolean;
+ ariaLabel?: string;
+ legend?: { items: ChartLegendItem[] };
+ tooltipHeading?: (label: string) => string;
+ tooltipValueLabel?: string;
+ barSpacing: "default" | "histogram";
+};
+
+// Shared chart mechanics for categorical bars and histogram bins; the public
+// components fix spacing to match their respective data semantics.
+export function BarChartCore({
+ data,
+ valueFormatter = (value) => value.toLocaleString(),
+ color = "hsl(var(--chart-1))",
+ variant = "default",
+ hideXAxisLabels = false,
+ zeroBaseline = true,
+ ariaLabel = "Bar chart",
+ legend,
+ tooltipHeading,
+ tooltipValueLabel,
+ barSpacing,
+}: BarChartCoreProps) {
+ const firstColor = data[0]?.color ?? color;
+ const hasDistinctColors = data.some(
+ (datum) => (datum.color ?? color) !== firstColor,
+ );
+
+ return (
+ <div className="flex size-full min-w-0 flex-col">
+ <div className="min-h-0 flex-1">
+ <ChartContainer>
+ {({ width, height }) => (
+ <CartesianLayout
+ width={width}
+ height={height}
+ showXAxisLabels={!hideXAxisLabels}
+ >
+ {({ measuredPlot, maxYTicks, plotForTicks }) => {
+ const values = data.flatMap((datum) =>
+ typeof datum.value === "number" &&
+ Number.isFinite(datum.value)
+ ? [datum.value]
+ : [],
+ );
+ const min = values.length ? Math.min(...values) : 0;
+ const max = values.length ? Math.max(...values) : 1;
+ const domainMin = zeroBaseline ? Math.min(0, min) : min;
+ const domainMax = Math.max(
+ zeroBaseline || min < 0 ? 0 : min,
+ max,
+ );
+ const domainPadding = Math.max(Math.abs(domainMin) * 0.1, 1);
+ const plotHeight = measuredPlot.height;
+ const yScale = scaleLinear()
+ .domain(
+ domainMin === domainMax
+ ? [domainMin - domainPadding, domainMax + domainPadding]
+ : [domainMin, domainMax],
+ )
+ .nice(maxYTicks)
+ .range([measuredPlot.top + plotHeight, measuredPlot.top]);
+ const yTicks = yScale.ticks(maxYTicks);
+ const plot = plotForTicks(yTicks.map(valueFormatter));
+ const leftMargin = plot.left;
+ const plotWidth = plot.width;
+ const xScale = scaleBand<number>()
+ .domain(data.map((_, index) => index))
+ .range([leftMargin, leftMargin + plotWidth])
+ .paddingInner(barSpacing === "histogram" ? 0 : 0.2)
+ .paddingOuter(barSpacing === "histogram" ? 0 : 0.1);
+ const baseline = yScale(
+ zeroBaseline || min < 0 ? 0 : (yScale.domain()[0] ?? 0),
+ );
+ const xTicks = data.map((datum, index) => ({
+ key: String(index),
+ x: (xScale(index) ?? leftMargin) + xScale.bandwidth() / 2,
+ label: datum.label,
+ maxWidth: xScale.bandwidth() - 8,
+ }));
+
+ if (
+ width <= 0 ||
+ height <= 0 ||
+ plotWidth <= 0 ||
+ plotHeight <= 0
+ ) {
+ return (
+ <svg width={width} height={height} aria-hidden="true" />
+ );
+ }
+
+ if (barSpacing === "histogram" && xScale.bandwidth() < 1) {
+ return (
+ <div className="text-muted-foreground absolute inset-0 flex items-center justify-center p-4 text-center">
+ Insufficient space
+ </div>
+ );
+ }
+
+ const histogramInset =
+ barSpacing === "histogram" && xScale.bandwidth() >= 3 ? 1 : 0;
+
+ return (
+ <ChartTooltip>
+ {({ activeIndex, getReferenceProps }) => (
+ <CartesianChart
+ width={width}
+ height={height}
+ ariaLabel={ariaLabel}
+ overflow="hidden"
+ plot={plot}
+ yTicks={yTicks}
+ y={yScale}
+ valueFormatter={valueFormatter}
+ zeroY={min < 0 ? yScale(0) : undefined}
+ xAxis={
+ hideXAxisLabels
+ ? undefined
+ : {
+ ticks: xTicks,
+ activeKey:
+ activeIndex === undefined
+ ? undefined
+ : String(activeIndex),
+ showCategoryTicks: true,
+ alignment: "center",
+ }
+ }
+ >
+ {data.map((datum, index) => {
+ const x = xScale(index);
+ if (x === undefined) return null;
+ const barColor = datum.color ?? color;
+ const y =
+ datum.value !== null && Number.isFinite(datum.value)
+ ? yScale(datum.value)
+ : baseline;
+ const barTop = Math.min(y, baseline);
+ const barHeight = Math.abs(y - baseline);
+ const active = activeIndex === index;
+ let colorStrength = 100;
+ if (variant === "subtle") {
+ colorStrength = active ? 60 : 30;
+ }
+ if (activeIndex !== undefined && !active) {
+ colorStrength = variant === "subtle" ? 15 : 20;
+ }
+ const fill =
+ colorStrength === 100
+ ? barColor
+ : `color-mix(in srgb, ${barColor} ${colorStrength}%, hsl(var(--background)))`;
+ return (
+ <g key={index}>
+ {datum.value !== null &&
+ Number.isFinite(datum.value) ? (
+ <rect
+ x={x + histogramInset}
+ y={barTop}
+ width={
+ xScale.bandwidth() - histogramInset * 2
+ }
+ height={Math.max(1, barHeight)}
+ rx={
+ barSpacing === "histogram"
+ ? 0
+ : Math.min(4, barHeight / 2)
+ }
+ fill={fill}
+ role="graphics-symbol"
+ tabIndex={0}
+ aria-label={`${datum.label}: ${valueFormatter(datum.value)}`}
+ className="outline-hidden transition-[fill] duration-150 focus-visible:outline-2 focus-visible:outline-offset-2"
+ {...getReferenceProps({
+ type: "primary",
+ index,
+ label: tooltipValueLabel ?? datum.label,
+ value: valueFormatter(datum.value),
+ heading: tooltipHeading?.(datum.label),
+ color: hasDistinctColors
+ ? barColor
+ : undefined,
+ })}
+ />
+ ) : null}
+ </g>
+ );
+ })}
+ </CartesianChart>
+ )}
+ </ChartTooltip>
+ );
+ }}
+ </CartesianLayout>
+ )}
+ </ChartContainer>
+ </div>
+ {legend?.items.length ? <ChartLegend items={legend.items} /> : null}
+ </div>
+ );
+}
diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsx
index a1c8012931..72ed2f11a9 100644
--- a/web/src/features/dashboard/components/ChartScores.tsx
+++ b/web/src/features/dashboard/components/ChartScores.tsx
@@ -25,7 +25,6 @@ import { useScheduledDashboardExecuteQuery } from "@/src/features/dashboard/hook
const SCORES_CHART_CONFIG = {
type: "LINE_TIME_SERIES",
show_data_point_dots: false,
- subtle_fill: true,
} as const;
export function ChartScores(props: {
diff --git a/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx b/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx
index 767c828735..ee5a4ad2e4 100644
--- a/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx
@@ -25,7 +25,6 @@ export const DashboardLineTimeSeriesChart = React.memo(
unit,
legendSummary,
syncId,
- subtleFill,
missingValue,
}: {
data: TimeSeriesChartDataPoint[];
@@ -33,7 +32,6 @@ export const DashboardLineTimeSeriesChart = React.memo(
unit?: string;
legendSummary?: LegendSummaryMode;
syncId?: string;
- subtleFill?: boolean;
/** See {@link MissingBucketValue}. Defaults to `"gap"`. */
missingValue?: MissingBucketValue;
}) {
@@ -47,9 +45,8 @@ export const DashboardLineTimeSeriesChart = React.memo(
type: "LINE_TIME_SERIES" as const,
unit,
show_data_point_dots: false,
- subtle_fill: subtleFill,
}),
- [unit, subtleFill],
+ [unit],
);
return (
diff --git a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
index 3229c08d79..214811829a 100644
--- a/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/CategoricalScoreChart.tsx
@@ -115,7 +115,6 @@ export function CategoricalScoreChart(props: {
chartConfig={{
type: "VERTICAL_BAR",
row_limit: 100,
- subtle_fill: true,
}}
/>
</div>
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
index 44564e3226..7c8c5c90f7 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreHistogram.tsx
@@ -72,7 +72,7 @@ export function NumericScoreHistogram(props: {
chartType="HISTOGRAM"
data={scoreHistogramToDataPoints(chartData, chartLabels)}
rowLimit={100}
- chartConfig={{ type: "HISTOGRAM", subtle_fill: true }}
+ chartConfig={{ type: "HISTOGRAM" }}
/>
</div>
);
diff --git a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
index 16ff9726b6..9dc843a849 100644
--- a/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/score-analytics/NumericScoreTimeSeriesChart.tsx
@@ -112,7 +112,6 @@ export function NumericScoreTimeSeriesChart(props: {
<div className="h-80 w-full shrink-0">
<DashboardLineTimeSeriesChart
data={extractedScores}
- subtleFill
syncId={props.syncId}
/>
</div>
diff --git a/web/src/features/widgets/chart-library/HistogramChart.tsx b/web/src/features/widgets/chart-library/HistogramChart.tsx
index 144981c2a7..995a0b9863 100644
--- a/web/src/features/widgets/chart-library/HistogramChart.tsx
+++ b/web/src/features/widgets/chart-library/HistogramChart.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import { HistogramChart as DesignSystemHistogramChart } from "@/src/components/design-system/charts/HistogramChart/HistogramChart";
import {
type DataPoint,
type MetricFormatterFunction,
@@ -7,21 +7,7 @@ import {
formatMetric,
toFullMetricString,
} from "@/src/features/widgets/chart-library/utils";
-import { BarChart, Bar, XAxis, YAxis } from "recharts";
-import {
- type ChartConfig,
- ChartContainer,
- ChartTooltip,
- ChartTooltipContent,
-} from "@/src/components/ui/chart";
-
-interface HistogramDataPoint {
- binLabel: string;
- count: number;
- lower?: number;
- upper?: number;
- height?: number;
-}
+import { type ChartConfig } from "@/src/components/ui/chart";
const HistogramChart = ({
data,
@@ -42,28 +28,22 @@ const HistogramChart = ({
const formatBinEdge = (value: number) =>
toFullMetricString(metricFormatter(value, { style: "compact" }));
- const transformHistogramData = (data: DataPoint[]): HistogramDataPoint[] => {
+ const transformHistogramData = (data: DataPoint[]) => {
if (!data.length) return [];
- // Check if this is ClickHouse histogram format (array of tuples)
const firstDataPoint = data[0];
if (firstDataPoint?.metric && Array.isArray(firstDataPoint.metric)) {
- // ClickHouse histogram format: [(lower, upper, height), ...]
return (firstDataPoint.metric as [number, number, number][]).map(
([lower, upper, height]) => ({
- binLabel: `[${formatBinEdge(lower)}, ${formatBinEdge(upper)}]`,
- count: height,
- lower,
- upper,
- height,
+ label: `[${formatBinEdge(lower)}, ${formatBinEdge(upper)}]`,
+ value: height,
}),
);
}
- // Fallback: treat as regular data points with binLabel
- return data.map((item) => ({
- binLabel: item.dimension || `Bin ${data.indexOf(item) + 1}`,
- count: (item.metric as number) || 0,
+ return data.map((item, index) => ({
+ label: item.dimension || `Bin ${index + 1}`,
+ value: (item.metric as number) || 0,
}));
};
@@ -78,58 +58,17 @@ const HistogramChart = ({
}
return (
- <ChartContainer
- config={config}
- className="[&_.recharts-bar-rectangle:hover]:opacity-30 dark:[&_.recharts-bar-rectangle:hover]:opacity-100 dark:[&_.recharts-bar-rectangle:hover]:brightness-[3]"
- >
- <BarChart
- data={histogramData}
- margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
- >
- <XAxis
- dataKey="binLabel"
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- angle={-45}
- textAnchor="end"
- height={90}
- />
- <YAxis
- stroke="hsl(var(--chart-grid))"
- fontSize={12}
- tickLine={false}
- axisLine={false}
- niceTicks="auto"
- />
- <Bar
- dataKey="count"
- fill="hsl(var(--chart-1))"
- radius={[2, 2, 0, 0]}
- fillOpacity={subtleFill ? 0.3 : 1}
- isAnimationActive={false}
- />
- <ChartTooltip
- cursor={false}
- contentStyle={{ backgroundColor: "hsl(var(--background))" }}
- content={({ active, payload, label }) => (
- <ChartTooltipContent
- active={active}
- payload={payload}
- label={label}
- valueFormatter={(v) =>
- toFullMetricString(
- formatMetric(Number(v), { style: "compact" }),
- )
- }
- nameFormatter={(name) => (name === "count" ? "Count" : name)}
- labelFormatter={(label) => `Bin: ${label}`}
- />
- )}
- />
- </BarChart>
- </ChartContainer>
+ <DesignSystemHistogramChart
+ data={histogramData}
+ color={config.count?.color ?? "hsl(var(--chart-1))"}
+ variant={subtleFill ? "subtle" : "default"}
+ valueFormatter={(value) =>
+ toFullMetricString(formatMetric(value, { style: "compact" }))
+ }
+ ariaLabel="Histogram"
+ tooltipHeading={(label) => `Bin: ${label}`}
+ tooltipValueLabel="Count"
+ />
);
};