Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(widgets): polish charts β€” stable tooltips, vertical grid lines, auto legends (LFE-10576) (#14848)

Nikita Kabardin770fd8076086
diff --git a/web/src/components/ui/chart.tsx b/web/src/components/ui/chart.tsx
index ad69955ad4..c1d26cb16d 100644
--- a/web/src/components/ui/chart.tsx
+++ b/web/src/components/ui/chart.tsx
@@ -262,7 +262,12 @@ const ChartTooltipContent = React.forwardRef<
key={String(item.dataKey ?? item.name ?? index)}
className={cn(
"[&>svg]:text-muted-foreground flex w-full items-center gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
- highlighted && "bg-muted -mx-1.5 rounded px-1.5",
+ // Emphasis must be layout-neutral: the row keeps its exact box
+ // and the highlight paints around it (a box-shadow halo adds
+ // the breathing room margins/padding would), so rows never
+ // shift or re-truncate when the hovered series changes. (LFE-10576)
+ highlighted &&
+ "bg-muted rounded-xs shadow-[0_0_0_3px_hsl(var(--muted))]",
)}
>
{formatter && item?.value !== undefined && item.name != null ? (
@@ -298,7 +303,11 @@ const ChartTooltipContent = React.forwardRef<
)}
<div
className={cn(
- "flex min-w-0 flex-1 justify-between gap-x-3 leading-none",
+ // leading-tight, not leading-none: `truncate` clips at
+ // the line box, and a 1.0 line-height leaves no room
+ // below the baseline β€” g/y/p descenders lost their
+ // bottom pixel. (LFE-10576)
+ "flex min-w-0 flex-1 justify-between gap-x-3 leading-tight",
nestLabel ? "items-end" : "items-center",
)}
>
@@ -307,7 +316,10 @@ const ChartTooltipContent = React.forwardRef<
<span
className={cn(
"text-muted-foreground truncate",
- highlighted && "text-foreground font-medium",
+ // Color-only emphasis: a weight change alters text
+ // metrics, so the highlighted name would truncate
+ // differently than its neighbors. (LFE-10576)
+ highlighted && "text-foreground",
)}
title={itemDisplayTitle}
>
@@ -334,13 +346,34 @@ const ChartTooltipContent = React.forwardRef<
);
ChartTooltipContent.displayName = "ChartTooltip";
+/** Horizontal gap between the hovered point and the tooltip's near edge. */
+const TOOLTIP_GAP_PX = 14;
+/**
+ * Upper bound on the tooltip's width. Coordinates the two decisions that used
+ * to fight each other: the side choice below guarantees the chosen side has
+ * this much room whenever any side does, and the box never asks for more β€” so
+ * hovering across a chart can't hit the "placed left but sized by the space on
+ * the right" squeeze. Long series names past this truncate (full name in the
+ * row's `title`). (LFE-10576)
+ */
+const TOOLTIP_MAX_WIDTH_PX = 448;
+
/**
* Renders a chart tooltip into the app's `tooltip` overlay layer (see
* `ui/layer.tsx`) so it escapes the chart card's `overflow` clipping and always
* paints on top β€” never cut off at the chart frame. Positioned at the hovered
* point (recharts' `coordinate`, relative to the chart box) translated to screen
- * coordinates, and flipped to the left near the right edge of the viewport.
- * (LFE-10549)
+ * coordinates. (LFE-10549)
+ *
+ * Side placement and sizing are ONE decision: the tooltip goes right of the
+ * point unless a full-width tooltip no longer fits there and the left side is
+ * larger. Crucially the box is anchored by the edge NEAREST the point (`left`
+ * when placed right, `right` when placed left) β€” never positioned at the point
+ * and then translated across it. A translate happens after layout, so a
+ * left-flipped tooltip laid out at `left: x` would still shrink-to-fit against
+ * the RIGHT viewport edge and ellipsize every row at exactly the x-positions
+ * where it flips. Anchoring by the near edge makes the browser size it against
+ * the side it actually occupies. (LFE-10576)
*/
function ChartTooltipPortal({
active,
@@ -367,10 +400,12 @@ function ChartTooltipPortal({
const rect = anchor.getBoundingClientRect();
const x = rect.left + coordinate.x;
const y = rect.top + coordinate.y;
- // Flip past the cursor near the right edge; anchor the tooltip's bottom/top to
- // the point near the viewport's bottom/top so a tall multi-series tooltip can't
- // spill its rows out of view (the overlay layer no longer clips it). (LFE-10549)
- const flipLeft = x > window.innerWidth * 0.6;
+ const spaceRight = window.innerWidth - x - TOOLTIP_GAP_PX;
+ const spaceLeft = x - TOOLTIP_GAP_PX;
+ const flipLeft = spaceRight < TOOLTIP_MAX_WIDTH_PX && spaceLeft > spaceRight;
+ // Anchor the tooltip's bottom/top to the point near the viewport's
+ // bottom/top so a tall multi-series tooltip can't spill its rows out of view
+ // (the overlay layer no longer clips it). (LFE-10549)
const translateY =
y > window.innerHeight * 0.65
? "-100%"
@@ -383,9 +418,12 @@ function ChartTooltipPortal({
<div
style={{
position: "fixed",
- left: x,
+ ...(flipLeft
+ ? { right: window.innerWidth - x + TOOLTIP_GAP_PX }
+ : { left: x + TOOLTIP_GAP_PX }),
top: y,
- transform: `translate(${flipLeft ? "calc(-100% - 14px)" : "14px"}, ${translateY})`,
+ maxWidth: TOOLTIP_MAX_WIDTH_PX,
+ transform: `translateY(${translateY})`,
pointerEvents: "none",
}}
>
diff --git a/web/src/features/dashboard/components/ChartScores.tsx b/web/src/features/dashboard/components/ChartScores.tsx
index 79f6e09616..9258693915 100644
--- a/web/src/features/dashboard/components/ChartScores.tsx
+++ b/web/src/features/dashboard/components/ChartScores.tsx
@@ -124,7 +124,6 @@ export function ChartScores(props: {
data={chartData}
rowLimit={100}
chartConfig={SCORES_CHART_CONFIG}
- legendPosition="above"
syncId={props.syncId}
/>
</div>
diff --git a/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx b/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx
index 90d0c9ff3f..21f0b46432 100644
--- a/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx
+++ b/web/src/features/dashboard/components/DashboardLineTimeSeriesChart.tsx
@@ -59,7 +59,6 @@ export const DashboardLineTimeSeriesChart = React.memo(
config={config}
rowLimit={100}
chartConfig={chartConfig}
- legendPosition="above"
legendSummary={legendSummary}
syncId={syncId}
missingValue={missingValue}
diff --git a/web/src/features/datasets/components/DatasetRunsTable.tsx b/web/src/features/datasets/components/DatasetRunsTable.tsx
index f92694d8f5..c4783521c9 100644
--- a/web/src/features/datasets/components/DatasetRunsTable.tsx
+++ b/web/src/features/datasets/components/DatasetRunsTable.tsx
@@ -693,9 +693,6 @@ export function DatasetRunsTable(props: {
type: chartType,
unit: getCompareViewChartUnit(key),
}}
- legendPosition={
- chartLabels.length > 1 ? "above" : "none"
- }
/>
</div>
</div>
diff --git a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
index e707518c47..4ef96f03f9 100644
--- a/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/AreaChartTimeSeries.tsx
@@ -41,7 +41,7 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
},
accessibilityLayer = true,
metricFormatter = (value, options) => formatMetric(value, options),
- legendPosition = "none",
+ legendPosition = "auto",
legendSummary = "none",
legendInteraction = "highlight",
maxVisibleSeries,
@@ -90,6 +90,7 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
const { legendItems, onLegendClick, isRendered, isDimmed } = useSeriesLegend({
data,
dimensions,
+ config,
legendSummary,
legendInteraction,
maxVisibleSeries,
@@ -116,14 +117,6 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
setSelfHovered(false);
}}
>
- {legendPosition === "above" && (
- <TimeSeriesLegend
- items={legendItems}
- interaction={legendInteraction}
- onItemClick={onLegendClick}
- formatSummary={tooltipFormatter}
- />
- )}
<SeriesOverflowNote
visibleCount={dimensions.length}
totalCount={series.total}
@@ -139,7 +132,14 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
syncId={syncId}
syncMethod="value"
>
- <CartesianGrid stroke="hsl(var(--chart-grid))" vertical={false} />
+ {/* syncWithTicks: grid lines sit exactly on the budget-thinned axis
+ ticks (a line per shown day/hour), instead of recharts' default
+ every-bucket grid β€” density follows the tick budget. (LFE-10576) */}
+ <CartesianGrid
+ stroke="hsl(var(--chart-grid))"
+ vertical={timeAxis.showVerticalGrid}
+ syncWithTicks
+ />
<XAxis
dataKey="time_dimension"
stroke="hsl(var(--chart-grid))"
@@ -211,6 +211,15 @@ export const AreaChartTimeSeries: React.FC<ChartProps> = ({
/>
</AreaChart>
</ChartContainer>
+ {(legendPosition === "below" ||
+ (legendPosition === "auto" && legendItems.length > 1)) && (
+ <TimeSeriesLegend
+ items={legendItems}
+ interaction={legendInteraction}
+ onItemClick={onLegendClick}
+ formatSummary={tooltipFormatter}
+ />
+ )}
</div>
);
};
diff --git a/web/src/features/widgets/chart-library/Chart.tsx b/web/src/features/widgets/chart-library/Chart.tsx
index 7cabea87fa..83c9e83944 100644
--- a/web/src/features/widgets/chart-library/Chart.tsx
+++ b/web/src/features/widgets/chart-library/Chart.tsx
@@ -4,6 +4,7 @@ import {
type MetricFormatterFunction,
type DataPoint,
type ChartThreshold,
+ type LegendPosition,
type LegendSummaryMode,
type LegendInteraction,
type MissingBucketValue,
@@ -69,7 +70,7 @@ const ChartComponent = ({
sortState?: OrderByState | null;
onSortChange?: (sortState: OrderByState | null) => void;
isLoading?: boolean;
- legendPosition?: "above" | "none";
+ legendPosition?: LegendPosition;
legendSummary?: LegendSummaryMode;
legendInteraction?: LegendInteraction;
maxVisibleSeries?: number;
diff --git a/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsx b/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsx
index 967318d826..6e6341ac5d 100644
--- a/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsx
+++ b/web/src/features/widgets/chart-library/ChartInteractivity.stories.tsx
@@ -87,7 +87,7 @@ const SyncedDashboardDemo = ({
<LineChartTimeSeries
data={panel.data}
syncId={syncId}
- legendPosition="above"
+ legendPosition="below"
legendSummary="none"
showDataPointDots={false}
metricFormatter={panel.formatter}
@@ -124,7 +124,7 @@ export const Spaghetti = meta.story({
<div className="h-[330px] w-full">
<LineChartTimeSeries
data={spaghettiData}
- legendPosition="above"
+ legendPosition="below"
legendSummary="none"
showDataPointDots={false}
metricFormatter={msFormatter}
diff --git a/web/src/features/widgets/chart-library/ChartPolish.stories.tsx b/web/src/features/widgets/chart-library/ChartPolish.stories.tsx
new file mode 100644
index 0000000000..a3d6d9fd12
--- /dev/null
+++ b/web/src/features/widgets/chart-library/ChartPolish.stories.tsx
@@ -0,0 +1,316 @@
+import preview from "../../../../.storybook/preview";
+import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
+import { ChartContainer } from "@/src/components/ui/chart";
+import { LineChartTimeSeries } from "./LineChartTimeSeries";
+import { VerticalBarChartTimeSeries } from "./VerticalBarChartTimeSeries";
+import { seriesColor } from "./TimeSeriesLegend";
+import {
+ formatMetric,
+ groupDataByTimeDimension,
+ toFullMetricString,
+} from "./utils";
+import {
+ type DataPoint,
+ type LegendPosition,
+ type ChartProps,
+} from "./chart-props";
+
+/**
+ * Decision surface for the LFE-10576 chart polish. Each story isolates one
+ * taste call (vertical grid density, bar-chart grid, default legend
+ * visibility) or one interactive fix (tooltip placement/sizing) on realistic
+ * data, so the choice is made by looking at renders, not diffs. Deterministic
+ * data only β€” no Math.random β€” so the renders are stable.
+ */
+
+// ── deterministic data ───────────────────────────────────────────────────────
+
+/** ISO timestamps so prepareTimeAxis picks the temporal (not category) axis. */
+const isoDay = (day: number, hour = 0) =>
+ new Date(Date.UTC(2026, 5, 22 + day, hour)).toISOString();
+
+const buildSeries = (
+ series: { name: string; base: number; amp: number }[],
+ buckets: number,
+ timeAt: (i: number) => string,
+): DataPoint[] => {
+ const points: DataPoint[] = [];
+ for (let i = 0; i < buckets; i++) {
+ const time = timeAt(i);
+ series.forEach(({ name, base, amp }, seed) => {
+ const wave = 0.5 + 0.5 * Math.sin((i + seed * 1.7) / 2.3);
+ const jitter = ((seed * 37 + i * 13) % 17) / 17;
+ points.push({
+ time_dimension: time,
+ dimension: name,
+ metric: Math.round(base + amp * wave + amp * 0.25 * jitter),
+ });
+ });
+ }
+ return points;
+};
+
+const MODELS = [
+ { name: "gpt-4o", base: 40_000, amp: 30_000 },
+ { name: "claude-3-5-sonnet", base: 25_000, amp: 18_000 },
+ { name: "gpt-4o-mini", base: 90_000, amp: 60_000 },
+ { name: "llama-3-70b", base: 12_000, amp: 9_000 },
+];
+
+/** 14 daily buckets β†’ date-mode axis ("Jun 22" … "Jul 5"). */
+const dailyData = buildSeries(MODELS, 14, (i) => isoDay(i));
+/** 24 hourly buckets in one day β†’ time-mode axis ("2 AM" … "11 PM"). */
+const hourlyData = buildSeries(MODELS, 24, (i) => isoDay(0, i));
+/** Single-series variant of the daily data. */
+const dailySingle = dailyData.filter((p) => p.dimension === "gpt-4o-mini");
+
+/** Long observation-type names β€” the tooltip-truncation stress case. */
+const longNameData = buildSeries(
+ [
+ { name: "sa-investigation:sa-evidence-verifier", base: 4_000, amp: 2_500 },
+ { name: "tool-bash-loghouse-querylog-reader", base: 28_000, amp: 9_000 },
+ { name: "step-loghouse-cplogs-aggregation-pass", base: 2_600, amp: 1_400 },
+ { name: "tool-bash-dwh-resolve-org-membership", base: 700, amp: 420 },
+ { name: "answer", base: 11_000, amp: 4_000 },
+ { name: "step-write-io", base: 6_300, amp: 2_100 },
+ ],
+ 14,
+ (i) => isoDay(i),
+);
+
+// ── shared framing ───────────────────────────────────────────────────────────
+
+const OptionCard = ({
+ label,
+ caption,
+ children,
+}: {
+ label: string;
+ caption: string;
+ children: React.ReactNode;
+}) => (
+ <div className="flex min-w-[340px] flex-1 flex-col gap-1">
+ <div className="text-xs font-bold tracking-wide uppercase">{label}</div>
+ <div className="bg-background h-[240px] w-full rounded-md border p-2">
+ {children}
+ </div>
+ <div className="text-muted-foreground w-full text-xs">{caption}</div>
+ </div>
+);
+
+/** A dashboard-widget-shaped card (title + description + plot). */
+const WidgetCard = ({
+ title,
+ description,
+ legendPosition,
+ data,
+}: {
+ title: string;
+ description: string;
+ legendPosition: LegendPosition;
+ data: DataPoint[];
+}) => (
+ <div className="bg-background flex h-[300px] w-[480px] flex-col rounded-lg border p-4">
+ <span className="truncate font-medium">{title}</span>
+ <div className="text-muted-foreground mb-2 truncate text-sm">
+ {description}
+ </div>
+ <div className="min-h-0 flex-1">
+ <LineChartTimeSeries data={data} legendPosition={legendPosition} />
+ </div>
+ </div>
+);
+
+/**
+ * Raw-recharts stacked bar twin of `VerticalBarChartTimeSeries`, with the grid
+ * exposed β€” the real component has NO grid today, so the variants have to be
+ * drawn side-by-side here for the decision.
+ */
+const BarGridVariant = ({
+ data,
+ grid,
+}: {
+ data: DataPoint[];
+ grid: "none" | "horizontal" | "both";
+}) => {
+ const grouped = groupDataByTimeDimension(data);
+ const dimensions = [...new Set(data.map((p) => p.dimension ?? ""))];
+ return (
+ // ChartContainer so tick text/grid pick up the same CSS the real chart
+ // gets β€” the variants must differ ONLY in the grid.
+ <ChartContainer config={{}}>
+ <BarChart data={grouped}>
+ {grid !== "none" && (
+ <CartesianGrid
+ stroke="hsl(var(--chart-grid))"
+ vertical={grid === "both"}
+ syncWithTicks
+ />
+ )}
+ <XAxis
+ dataKey="time_dimension"
+ stroke="hsl(var(--chart-grid))"
+ fontSize={12}
+ tickLine={false}
+ axisLine={false}
+ interval={2}
+ tickFormatter={(v: string) =>
+ new Date(v).toLocaleDateString("en-US", {
+ month: "short",
+ day: "numeric",
+ })
+ }
+ />
+ <YAxis
+ type="number"
+ stroke="hsl(var(--chart-grid))"
+ fontSize={12}
+ tickLine={false}
+ axisLine={false}
+ niceTicks="auto"
+ tickFormatter={(value: number) =>
+ toFullMetricString(formatMetric(value, { style: "compact" }))
+ }
+ />
+ {dimensions.map((dimension, index) => (
+ <Bar
+ key={dimension}
+ dataKey={dimension}
+ stackId="stack"
+ fill={seriesColor(index)}
+ isAnimationActive={false}
+ />
+ ))}
+ </BarChart>
+ </ChartContainer>
+ );
+};
+
+const ChartPolishDemo = (props: ChartProps) => (
+ <LineChartTimeSeries {...props} />
+);
+
+const meta = preview.meta({
+ title: "Design System/Charts/Polish (LFE-10576)",
+ component: ChartPolishDemo,
+});
+
+// ── β‘€ Vertical grid lines ────────────────────────────────────────────────────
+
+/**
+ * DECIDED (Nikita, 2026-07-07): vertical lines on ALL temporal scales. They
+ * land on the shown x ticks (`syncWithTicks`), so density follows the tick
+ * budget; categorical axes stay clean.
+ */
+export const GridVerticalLines = meta.story({
+ render: () => (
+ <div className="flex flex-wrap gap-5 p-1">
+ <OptionCard
+ label="Date scale (days)"
+ caption="One line per shown day tick β€” the ticket's ask."
+ >
+ <LineChartTimeSeries data={dailyData} legendPosition="none" />
+ </OptionCard>
+ <OptionCard
+ label="Time scale (hours)"
+ caption="Same rule zoomed into a day: a line per shown hour tick."
+ >
+ <LineChartTimeSeries data={hourlyData} legendPosition="none" />
+ </OptionCard>
+ </div>
+ ),
+});
+
+// ── β‘€b Bar chart grid ────────────────────────────────────────────────────────
+
+/** DECIDED (Nikita, 2026-07-07): horizontal only β€” first card is the real component. */
+export const BarChartGrid = meta.story({
+ render: () => (
+ <div className="flex flex-wrap gap-5 p-1">
+ <OptionCard
+ label="Adopted: horizontal only"
+ caption="y-gridlines make bar heights gaugeable; the bars themselves mark the x-rhythm."
+ >
+ <VerticalBarChartTimeSeries data={dailyData} legendPosition="none" />
+ </OptionCard>
+ <OptionCard
+ label="Rejected: no grid"
+ caption="The old bar time series β€” values were hard to gauge."
+ >
+ <BarGridVariant data={dailyData} grid="none" />
+ </OptionCard>
+ <OptionCard
+ label="Rejected: horizontal + vertical"
+ caption="Vertical lines fall between bars and only add noise."
+ >
+ <BarGridVariant data={dailyData} grid="both" />
+ </OptionCard>
+ </div>
+ ),
+});
+
+// ── β‘£ Default legend visibility ──────────────────────────────────────────────
+
+/**
+ * DECIDED (Nikita, 2026-07-07): default is "auto" β€” a legend only when the
+ * chart draws >1 series (a single-series legend just echoes the card title) β€”
+ * and a rendered legend sits BELOW the plot. Dashboard widgets used to never
+ * show a legend (old default "none") while the built-in home charts forced
+ * one; "auto" heals that inconsistency without call-site changes.
+ */
+export const LegendDefaultVisibility = meta.story({
+ render: () => (
+ <div className="flex flex-col gap-4 p-1">
+ <div className="flex flex-wrap gap-4">
+ <WidgetCard
+ title="Total tokens"
+ description="auto, single series β†’ no legend"
+ legendPosition="auto"
+ data={dailySingle}
+ />
+ <WidgetCard
+ title="Total tokens"
+ description='single series, legend forced on ("below")'
+ legendPosition="below"
+ data={dailySingle}
+ />
+ </div>
+ <div className="flex flex-wrap gap-4">
+ <WidgetCard
+ title="Total tokens by model"
+ description='4 series, legend opted out ("none")'
+ legendPosition="none"
+ data={dailyData}
+ />
+ <WidgetCard
+ title="Total tokens by model"
+ description="auto, 4 series β†’ legend below the plot"
+ legendPosition="auto"
+ data={dailyData}
+ />
+ </div>
+ </div>
+ ),
+});
+
+// ── β‘ β‘‘β‘’ Tooltip placement / sizing (interactive) ─────────────────────────────
+
+/**
+ * Live check for the tooltip fixes: sweep the cursor left↔right across the
+ * full chart width. The tooltip must keep a stable, readable width on both
+ * sides of the flip (no all-ellipsis collapse near the right edge), the
+ * proximity-highlighted row must not shift or re-truncate, and descenders
+ * (g/y/p) must not lose their bottom pixel.
+ */
+export const TooltipEdgePlacement = meta.story({
+ render: () => (
+ <div className="bg-background w-[95vw] rounded-md border p-3">
+ <div className="mb-1 text-sm font-medium">
+ Hover near the right edge β€” long names, viewport-wide chart
+ </div>
+ <div className="h-[300px] w-full">
+ <LineChartTimeSeries data={longNameData} legendPosition="below" />
+ </div>
+ </div>
+ ),
+});
diff --git a/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx b/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx
index ba6b34ec64..704bdb7919 100644
--- a/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx
+++ b/web/src/features/widgets/chart-library/ChartingPrinciples.stories.tsx
@@ -306,7 +306,7 @@ export const HoverTimeline = meta.story({
<LineChartTimeSeries
data={fewSeries}
syncId="charting-principles"
- legendPosition="above"
+ legendPosition="below"
showDataPointDots={false}
metricFormatter={msFormatter}
/>
@@ -319,7 +319,7 @@ export const HoverTimeline = meta.story({
{ name: "gpt-4o-mini", base: 22_000, amp: 8_000 },
])}
syncId="charting-principles"
- legendPosition="above"
+ legendPosition="below"
showDataPointDots={false}
/>
</ChartFrame>
@@ -333,7 +333,7 @@ export const QuietChrome = meta.story({
<ChartFrame title="High data-ink: faint grid, no axis spine, muted labels">
<LineChartTimeSeries
data={fewSeries}
- legendPosition="above"
+ legendPosition="below"
showDataPointDots={false}
metricFormatter={msFormatter}
/>
@@ -347,7 +347,7 @@ export const BoundTheFrame = meta.story({
<ChartFrame title="30 series in, 25 drawn β€” and it says so">
<LineChartTimeSeries
data={manySeries}
- legendPosition="above"
+ legendPosition="below"
showDataPointDots={false}
metricFormatter={msFormatter}
/>
@@ -524,7 +524,7 @@ export const IsolatedPoints = meta.story({
<LineChartTimeSeries
data={buildGappedData(isolatedPointSeries)}
missingValue="gap"
- legendPosition="above"
+ legendPosition="below"
metricFormatter={msFormatter}
/>
</ExampleCard>
@@ -543,7 +543,7 @@ export const StaggeredSeriesGaps = meta.story({
<LineChartTimeSeries
data={buildGappedData(staggeredGapSeries)}
missingValue="gap"
- legendPosition="above"
+ legendPosition="below"
metricFormatter={msFormatter}
/>
</ExampleCard>
@@ -562,7 +562,7 @@ export const EmptyBucketsStayOnAxis = meta.story({
<LineChartTimeSeries
data={buildGappedData(twoEras)}
missingValue="gap"
- legendPosition="above"
+ legendPosition="below"
/>
</ExampleCard>
<ExampleCard
@@ -573,7 +573,7 @@ export const EmptyBucketsStayOnAxis = meta.story({
<LineChartTimeSeries
data={buildGappedData(twoEras)}
missingValue="zero"
- legendPosition="above"
+ legendPosition="below"
legendSummary="sum"
/>
</ExampleCard>
diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx
index 0281de395e..761f011143 100644
--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx
+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.stories.tsx
@@ -70,7 +70,7 @@ const meta = preview.meta({
component: LineChartTimeSeriesDemo,
args: {
data: latencyData,
- legendPosition: "above",
+ legendPosition: "below",
metricFormatter: msFormatter,
},
// Host in a card-sized box so ResponsiveContainer has room (the widget shape).
diff --git a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
index b24a296a89..760567982a 100644
--- a/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/LineChartTimeSeries.tsx
@@ -192,7 +192,7 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({
},
accessibilityLayer = true,
metricFormatter = (value, options) => formatMetric(value, options),
- legendPosition = "none",
+ legendPosition = "auto",
legendSummary = "none",
legendInteraction = "highlight",
maxVisibleSeries,
@@ -252,6 +252,7 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({
} = useSeriesLegend({
data,
dimensions,
+ config,
legendSummary,
legendInteraction,
maxVisibleSeries,
@@ -292,14 +293,6 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({
setSelfHovered(false);
}}
>
- {legendPosition === "above" && (
- <TimeSeriesLegend
- items={legendItems}
- interaction={legendInteraction}
- onItemClick={onLegendClick}
- formatSummary={tooltipFormatter}
- />
- )}
<SeriesOverflowNote
visibleCount={dimensions.length}
totalCount={series.total}
@@ -315,7 +308,14 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({
syncId={syncId}
syncMethod="value"
>
- <CartesianGrid stroke="hsl(var(--chart-grid))" vertical={false} />
+ {/* syncWithTicks: grid lines sit exactly on the budget-thinned axis
+ ticks (a line per shown day/hour), instead of recharts' default
+ every-bucket grid β€” density follows the tick budget. (LFE-10576) */}
+ <CartesianGrid
+ stroke="hsl(var(--chart-grid))"
+ vertical={timeAxis.showVerticalGrid}
+ syncWithTicks
+ />
<XAxis
dataKey="time_dimension"
stroke="hsl(var(--chart-grid))"
@@ -409,6 +409,15 @@ export const LineChartTimeSeries: React.FC<ChartProps> = ({
/>
</LineChart>
</ChartContainer>
+ {(legendPosition === "below" ||
+ (legendPosition === "auto" && legendItems.length > 1)) && (
+ <TimeSeriesLegend
+ items={legendItems}
+ interaction={legendInteraction}
+ onItemClick={onLegendClick}
+ formatSummary={tooltipFormatter}
+ />
+ )}
</div>
);
};
diff --git a/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx b/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx
index 5cf1305629..5d8e1350a7 100644
--- a/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx
+++ b/web/src/features/widgets/chart-library/TimeSeriesLegend.tsx
@@ -1,10 +1,12 @@
import React, { useEffect, useMemo, useRef, useState } from "react";
+import { type ChartConfig } from "@/src/components/ui/chart";
import {
type DataPoint,
type LegendInteraction,
type LegendSummaryMode,
} from "@/src/features/widgets/chart-library/chart-props";
import { getDimensionSummaries } from "@/src/features/widgets/chart-library/utils";
+import { getPlainTextFromReactNode } from "@/src/utils/react-node-plain-text";
import { cn } from "@/src/utils/tailwind";
/** The 8-slot chart palette, cycled by series index (matches the series fills). */
@@ -13,6 +15,13 @@ export const seriesColor = (index: number): string =>
export type LegendItem = {
dimension: string;
+ /**
+ * Display label β€” the chart config's label for this series, falling back to
+ * the raw dimension: the same chain the tooltip resolves a row name through
+ * (`ChartTooltipContent`), so legend and tooltip can never disagree about
+ * what a series is called. (LFE-10576)
+ */
+ label: React.ReactNode;
/** Position in the dimension list β€” pins the swatch color to the series fill. */
colorIndex: number;
color: string;
@@ -35,12 +44,15 @@ export type LegendItem = {
export function useSeriesLegend({
data,
dimensions,
+ config,
legendSummary = "none",
legendInteraction = "highlight",
maxVisibleSeries,
}: {
data: DataPoint[];
dimensions: string[];
+ /** Resolves display labels (see {@link LegendItem.label}). */
+ config?: ChartConfig;
legendSummary?: LegendSummaryMode;
legendInteraction?: LegendInteraction;
maxVisibleSeries?: number;
@@ -114,6 +126,7 @@ export function useSeriesLegend({
const legendItems: LegendItem[] = dimensions.map((dimension, index) => ({
dimension,
+ label: config?.[dimension]?.label ?? dimension,
colorIndex: index,
color: seriesColor(index),
summary: summaries?.get(dimension) ?? null,
@@ -175,9 +188,12 @@ export function TimeSeriesLegend({
// Wrap onto multiple rows so every series stays visible, but cap the
// legend's height and scroll inside it β€” a chart with hundreds of series
// must never let the legend crowd the plot out entirely. (LFE-10549)
- <div className="[max-height:8rem] min-w-0 shrink-0 overflow-y-auto pb-3">
- <div className="flex flex-wrap justify-end gap-x-4 gap-y-1">
+ // Sits BELOW the plot (classic bottom-legend placement), so it pads
+ // against the x-axis above it. (LFE-10576)
+ <div className="[max-height:8rem] min-w-0 shrink-0 overflow-y-auto pt-2">
+ <div className="flex flex-wrap justify-center gap-x-4 gap-y-1">
{items.map((item) => {
+ const labelText = getPlainTextFromReactNode(item.label);
// Labels must describe the NEXT action, not the current state.
// - toggle: click flips visibility β†’ "Show"/"Hide".
// - highlight: clicking the focused series clears focus ("Show all
@@ -186,11 +202,11 @@ export function TimeSeriesLegend({
const ariaLabel =
interaction === "toggle"
? item.dimmed
- ? `Show ${item.dimension}`
- : `Hide ${item.dimension}`
+ ? `Show ${labelText}`
+ : `Hide ${labelText}`
: item.focused
? "Show all series"
- : `Show only ${item.dimension}`;
+ : `Show only ${labelText}`;
// aria-pressed reflects state: visible (toggle) / focused (highlight).
const ariaPressed =
interaction === "toggle" ? !item.dimmed : item.focused;
@@ -211,7 +227,7 @@ export function TimeSeriesLegend({
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{ backgroundColor: item.color }}
/>
- <span className="text-muted-foreground">{item.dimension}</span>
+ <span className="text-muted-foreground">{item.label}</span>
{item.summary !== null && (
<span className="text-foreground font-medium">
{formatSummary(item.summary)}
diff --git a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
index d8e709fe04..ca214a1b89 100644
--- a/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
+++ b/web/src/features/widgets/chart-library/VerticalBarChartTimeSeries.tsx
@@ -6,7 +6,7 @@ import {
ChartTooltipContent,
ChartTooltipPortal,
} from "@/src/components/ui/chart";
-import { Bar, BarChart, XAxis, YAxis } from "recharts";
+import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
import { type ChartProps } from "@/src/features/widgets/chart-library/chart-props";
import {
formatMetric,
@@ -42,7 +42,7 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
},
accessibilityLayer = true,
metricFormatter = (value, options) => formatMetric(value, options),
- legendPosition = "none",
+ legendPosition = "auto",
legendSummary = "none",
legendInteraction = "highlight",
maxVisibleSeries,
@@ -73,6 +73,7 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
const { legendItems, onLegendClick, isRendered, isDimmed } = useSeriesLegend({
data,
dimensions,
+ config,
legendSummary,
legendInteraction,
maxVisibleSeries,
@@ -101,14 +102,6 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
setSelfHovered(false);
}}
>
- {legendPosition === "above" && (
- <TimeSeriesLegend
- items={legendItems}
- interaction={legendInteraction}
- onItemClick={onLegendClick}
- formatSummary={formatValue}
- />
- )}
<SeriesOverflowNote
visibleCount={dimensions.length}
totalCount={series.total}
@@ -124,6 +117,14 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
syncId={syncId}
syncMethod="value"
>
+ {/* Horizontal only: y-gridlines make bar heights gaugeable like the
+ line/area charts; the bars themselves already mark the x-rhythm,
+ so vertical lines would only add noise between them. (LFE-10576) */}
+ <CartesianGrid
+ stroke="hsl(var(--chart-grid))"
+ vertical={false}
+ syncWithTicks
+ />
<XAxis
dataKey="time_dimension"
stroke="hsl(var(--chart-grid))"
@@ -185,6 +186,15 @@ export const VerticalBarChartTimeSeries: React.FC<ChartProps> = ({
/>
</BarChart>
</ChartContainer>
+ {(legendPosition === "below" ||
+ (legendPosition === "auto" && legendItems.length > 1)) && (
+ <TimeSeriesLegend
+ items={legendItems}
+ interaction={legendInteraction}
+ onItemClick={onLegendClick}
+ formatSummary={formatValue}
+ />
+ )}
</div>
);
};
diff --git a/web/src/features/widgets/chart-library/chart-props.ts b/web/src/features/widgets/chart-library/chart-props.ts
index b01521fb2e..96352c4d4c 100644
--- a/web/src/features/widgets/chart-library/chart-props.ts
+++ b/web/src/features/widgets/chart-library/chart-props.ts
@@ -29,7 +29,17 @@ export interface DataPoint {
*/
export type MissingBucketValue = "zero" | "gap";
-export type LegendPosition = "above" | "none";
+/**
+ * Whether a time-series chart shows its legend (always rendered below the
+ * plot):
+ * - `"auto"` (default): only when the chart draws more than one series β€” a
+ * multi-series chart is unreadable without one, while a single-series legend
+ * just echoes the card title.
+ * - `"below"`: always.
+ * - `"none"`: never.
+ * (LFE-10576)
+ */
+export type LegendPosition = "auto" | "below" | "none";
/**
* Whether a chart legend shows a per-series summary across its time buckets:
diff --git a/web/src/features/widgets/chart-library/prepareTimeAxis.clienttest.ts b/web/src/features/widgets/chart-library/prepareTimeAxis.clienttest.ts
index 292270d8b0..44cd11e120 100644
--- a/web/src/features/widgets/chart-library/prepareTimeAxis.clienttest.ts
+++ b/web/src/features/widgets/chart-library/prepareTimeAxis.clienttest.ts
@@ -20,6 +20,17 @@ describe("prepareTimeAxis", () => {
expect(MONTH_DAY.test(label)).toBe(false); // never a date on a time-scale tick
});
+ it("temporal axes opt into vertical grid lines; categorical axes stay clean", () => {
+ const start = Date.UTC(2026, 5, 28, 0);
+ const temporal = Array.from({ length: 24 }, (_, h) =>
+ iso(start + h * HOUR),
+ );
+ expect(prepareTimeAxis(temporal, 6).showVerticalGrid).toBe(true);
+
+ const categorical = ["run-alpha", "run-beta", "run-gamma"];
+ expect(prepareTimeAxis(categorical, 6).showVerticalGrid).toBe(false);
+ });
+
it("span >24h uses date mode (no hour-only ticks repeating across midnight)", () => {
// 36 hourly buckets β‰ˆ 35h span β€” must NOT be time mode (would duplicate hours).
const start = Date.UTC(2026, 5, 28, 0);
diff --git a/web/src/features/widgets/chart-library/prepareTimeAxis.ts b/web/src/features/widgets/chart-library/prepareTimeAxis.ts
index 7db8e98a38..5474e498c7 100644
--- a/web/src/features/widgets/chart-library/prepareTimeAxis.ts
+++ b/web/src/features/widgets/chart-library/prepareTimeAxis.ts
@@ -138,6 +138,17 @@ export type TimeAxis = {
/** Fuller label for the tooltip (always date + year, time when intraday). */
formatTooltip: (raw: unknown) => string;
mode: AxisMode;
+ /**
+ * Whether the chart draws vertical grid lines. True on temporal axes, where
+ * a line under each shown tick (a day/hour/month boundary) helps the eye
+ * carry a bucket up into the plot; the tick budget already thinned those
+ * ticks to what fits, so the lines inherit "only when there's space" (pair
+ * with recharts' `syncWithTicks` so lines land exactly on the shown ticks).
+ * False for categorical axes: their angled entity-name labels are kept by a
+ * width-dependent collision test, and gridlines under arbitrary names add
+ * noise, not orientation. (LFE-10576)
+ */
+ showVerticalGrid: boolean;
/**
* Tick-label props the visualiser spreads onto the recharts `XAxis`.
* Time / date / month ticks are short single-units rendered flat (`{}` β†’ the
@@ -198,6 +209,7 @@ export function prepareTimeAxis(rawValues: unknown[], maxTicks = 6): TimeAxis {
formatTick: (raw: unknown) => truncateCategoryLabel(full(raw)),
formatTooltip: full,
mode: "category",
+ showVerticalGrid: false,
tickProps: {
angle: -30,
textAnchor: "end",
@@ -282,5 +294,12 @@ export function prepareTimeAxis(rawValues: unknown[], maxTicks = 6): TimeAxis {
// Time / date / month ticks are short single-units β€” rendered flat, exactly
// as the dashboards do today (no orientation change β†’ pixel-identical).
- return { interval, formatTick, formatTooltip, mode, tickProps: {} };
+ return {
+ interval,
+ formatTick,
+ formatTooltip,
+ mode,
+ showVerticalGrid: true,
+ tickProps: {},
+ };
}
diff --git a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/charts.tsx b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/charts.tsx
index 4f7b0f575c..030a0cb51f 100644
--- a/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/charts.tsx
+++ b/web/src/pages/project/[projectId]/datasets/[datasetId]/compare/charts.tsx
@@ -244,9 +244,6 @@ export default function DatasetCompare() {
type: chartType,
unit: getCompareViewChartUnit(key),
}}
- legendPosition={
- chartLabels.length > 1 ? "above" : "none"
- }
/>
</div>
</div>