Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(insights): y-axis formatting for quill SQL charts (#65004)

Sam Penningtoncdcf893bfc17
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 86eb2a48354a..4c5c76090053 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -920,6 +920,10 @@ snapshots:
hash: v1.k794b7964.e332e9beb6b72bee51ab22b8078273883dabe8cd97163f6005a44367378fa8f7.H_JLql_NFDi4zX-Gn0svc0N_NewsyAhqaII4UGIXykg
components-hogcharts-timeserieslinechart--moving-average--light:
hash: v1.k794b7964.0f2a959431d87965b61c34c7c94e7763efca126790ad4e2b801aa1d93c20a72d.ksgPaHbh3FnmvIYPvD7eV3TPJWStnTOK0W4agTCWjBs
+ components-hogcharts-timeserieslinechart--start-at-zero--dark:
+ hash: v1.k794b7964.4ca03b8b9d38cc29aacf6a774fa3b16de3150f1d6d1674e868460fb682c45615.9TX1D55OcEdpyXEMDREHhwafpG_GgVQcShx2tN6EVw0
+ components-hogcharts-timeserieslinechart--start-at-zero--light:
+ hash: v1.k794b7964.5555a7f2c844b527657c5c6433813cb0c5be60a2d00220e080feeb3f4dbc4462.7Q96V72xBoOgDes5ncZ-Ip-Z3pc2pjSEFwdCD7SzGAs
components-hogcharts-timeserieslinechart--trend-lines--dark:
hash: v1.k794b7964.09e1e25dadb2f3d2679c69e4b3b93355e7036ec196ad5f2055f3b4b8fb0deca8.9F9Uu0KpaHYnwTZbbFrQLI4gfdIjbF1MLcNigcosFa4
components-hogcharts-timeserieslinechart--trend-lines--light:
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
new file mode 100644
index 000000000000..d6ef9836864b
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
@@ -0,0 +1,131 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, screen, waitFor } from '@testing-library/react'
+
+import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
+
+import { getHogChart, renderWithInsights } from '~/test/insight-testing'
+import { ChartDisplayType } from '~/types'
+
+import { AxisSeries } from '../../dataVisualizationLogic'
+import { LineGraphProps } from './LineGraph'
+import { SqlLineGraph } from './SqlLineGraph'
+
+type YSettings = AxisSeries<number | null>['settings']
+
+const stringColumn = (name: string): AxisSeries<string>['column'] => ({
+ name,
+ type: { name: 'STRING', isNumerical: false },
+ label: name,
+ dataIndex: 0,
+})
+
+const numericColumn = (name: string): AxisSeries<number | null>['column'] => ({
+ name,
+ type: { name: 'INTEGER', isNumerical: true },
+ label: name,
+ dataIndex: 1,
+})
+
+const xData = (labels: string[]): AxisSeries<string> => ({ column: stringColumn('label'), data: labels })
+
+const ySeries = (name: string, data: (number | null)[], settings: YSettings = {}): AxisSeries<number | null> => ({
+ column: numericColumn(name),
+ data,
+ settings,
+})
+
+const props = (overrides: Partial<LineGraphProps>): LineGraphProps => ({
+ xData: xData(['Mon', 'Tue', 'Wed']),
+ yData: [],
+ visualizationType: ChartDisplayType.ActionsLineGraph,
+ chartSettings: {},
+ ...overrides,
+})
+
+const renderChart = async (overrides: Partial<LineGraphProps>): Promise<void> => {
+ renderWithInsights({ component: <SqlLineGraph {...props(overrides)} /> })
+ await screen.findByRole('img', { name: /chart with/i })
+}
+
+const lowestTick = (ticks: string[]): number => Math.min(...ticks.map((t) => parseFloat(t.replace(/[^0-9.eE+-]/g, ''))))
+
+describe('SqlLineGraph', () => {
+ let cleanupJsdom: () => void
+ let cleanupRaf: () => void
+
+ beforeEach(() => {
+ cleanupJsdom = setupJsdom()
+ cleanupRaf = setupSyncRaf()
+ })
+
+ afterEach(() => {
+ cleanupRaf()
+ cleanupJsdom()
+ cleanup()
+ })
+
+ describe('y-axis tick formatting', () => {
+ const waitForYTicks = async (): Promise<string[]> => {
+ await waitFor(() => expect(getHogChart().yTicks().length).toBeGreaterThan(0))
+ return getHogChart().yTicks()
+ }
+
+ it('applies the column prefix/suffix to the left-axis ticks', async () => {
+ await renderChart({
+ yData: [ySeries('revenue', [1200, 1400, 1300], { formatting: { prefix: '$' } })],
+ })
+
+ const ticks = await waitForYTicks()
+ expect(ticks.every((tick) => tick.startsWith('$'))).toBe(true)
+ })
+
+ it('keeps quill auto-formatted ticks when the column carries no formatting', async () => {
+ await renderChart({ yData: [ySeries('count', [1200, 1400, 1300])] })
+
+ const ticks = await waitForYTicks()
+ expect(ticks.some((tick) => /[$%]/.test(tick))).toBe(false)
+ })
+
+ it('formats each gutter from its own column on a dual-axis chart', async () => {
+ await renderChart({
+ yData: [
+ ySeries('revenue', [1200, 1400, 1300], { formatting: { prefix: '$' } }),
+ ySeries('conversion', [12, 18, 15], {
+ formatting: { suffix: '%' },
+ display: { yAxisPosition: 'right' },
+ }),
+ ],
+ })
+
+ await waitFor(() => expect(getHogChart().hasRightAxis).toBe(true))
+ const chart = getHogChart()
+ const rightTicks = chart.yRightTicks()
+ expect(chart.yTicks().every((tick) => tick.startsWith('$'))).toBe(true)
+ expect(rightTicks.length).toBeGreaterThan(0)
+ expect(rightTicks.every((tick) => tick.endsWith('%'))).toBe(true)
+ })
+ })
+
+ describe('start at zero', () => {
+ const waitForYTicks = async (): Promise<string[]> => {
+ await waitFor(() => expect(getHogChart().yTicks().length).toBeGreaterThan(0))
+ return getHogChart().yTicks()
+ }
+
+ it('clamps the left-axis baseline to 0 by default', async () => {
+ await renderChart({ yData: [ySeries('latency', [820, 860, 840])] })
+
+ expect(lowestTick(await waitForYTicks())).toBe(0)
+ })
+
+ it('floats the left axis to the data range when startAtZero is false', async () => {
+ await renderChart({
+ yData: [ySeries('latency', [820, 860, 840])],
+ chartSettings: { leftYAxisSettings: { startAtZero: false } },
+ })
+
+ expect(lowestTick(await waitForYTicks())).toBeGreaterThan(0)
+ })
+ })
+})
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
index 924900e3dd2e..7be857ad4e4a 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -1,4 +1,6 @@
-import { type TooltipContext, type TrendLineConfig } from '@posthog/quill-charts'
+import { type TooltipContext, type TrendLineConfig, type YAxisConfig } from '@posthog/quill-charts'
+
+import { compactNumber } from 'lib/utils/numbers'
import { ChartSettings, GoalLine } from '~/queries/schema/schema-general'
import { ChartDisplayType } from '~/types'
@@ -24,6 +26,7 @@ import {
comboBarLayoutForDisplay,
exceedsMaxSeries,
formatSqlSeriesValue,
+ hasAxisTickFormatting,
hasMixedSeriesTypes,
seriesDisplayType,
} from './sqlLineGraphAdapter'
@@ -442,6 +445,23 @@ describe('sqlLineGraphAdapter', () => {
})
})
+ describe('hasAxisTickFormatting', () => {
+ it.each<[string, AxisSeries<number | null>['settings'], boolean]>([
+ ['undefined settings', undefined, false],
+ ['no formatting block', { display: { color: '#abc' } }, false],
+ ['default empty prefix/suffix', { formatting: { prefix: '', suffix: '' } }, false],
+ ['style none', { formatting: { style: 'none' } }, false],
+ ['style number', { formatting: { style: 'number' } }, true],
+ ['style short', { formatting: { style: 'short' } }, true],
+ ['style percent', { formatting: { style: 'percent' } }, true],
+ ['prefix', { formatting: { prefix: '$' } }, true],
+ ['suffix', { formatting: { suffix: ' req' } }, true],
+ ['decimal places', { formatting: { decimalPlaces: 2 } }, true],
+ ])('returns %s -> %s', (_name, settings, expected) => {
+ expect(hasAxisTickFormatting(settings)).toBe(expected)
+ })
+ })
+
describe('buildSqlTooltipConfig', () => {
const entry = (settings: AxisSeries<number | null>['settings']): TooltipContext['seriesData'][number] => ({
series: { key: 'r', label: 'Revenue', data: [1200], meta: { settings } },
@@ -523,11 +543,70 @@ describe('sqlLineGraphAdapter', () => {
}
const config = buildLineChartConfig({ xData: dateXData, chartSettings, timezone: 'UTC', ySeriesData })
expect(config.yAxis).toEqual([
+ // Left is logarithmic, so startAtZero is omitted (no zero baseline on a log scale).
{ id: 'left', position: 'left', label: 'Left', scale: 'log', showGrid: true, hide: false },
- { id: 'right', position: 'right', label: 'Right', scale: 'linear', showGrid: false, hide: false },
+ {
+ id: 'right',
+ position: 'right',
+ label: 'Right',
+ scale: 'linear',
+ showGrid: false,
+ hide: false,
+ startAtZero: true,
+ },
])
})
+ it('formats each gutter from a series on that axis and starts linear axes at zero', () => {
+ const config = buildLineChartConfig({
+ xData: dateXData,
+ chartSettings: {},
+ timezone: 'UTC',
+ ySeriesData: [
+ ySeries('revenue', [1200, 1400], { formatting: { prefix: '$' } }),
+ ySeries('conversion', [12, 18], {
+ formatting: { suffix: '%' },
+ display: { yAxisPosition: 'right' },
+ }),
+ ],
+ })
+ const yAxis = config.yAxis as YAxisConfig[]
+ expect(Array.isArray(yAxis)).toBe(true)
+ expect(yAxis[0].tickFormatter?.(1200)).toBe('$1200')
+ expect(yAxis[1].tickFormatter?.(18)).toBe('18%')
+ expect(yAxis[0].startAtZero).toBe(true)
+ })
+
+ it('formats single-axis ticks from the first series column and defaults startAtZero on', () => {
+ const config = buildLineChartConfig({
+ xData: dateXData,
+ chartSettings: {},
+ timezone: 'UTC',
+ ySeriesData: [ySeries('revenue', [1200], { formatting: { prefix: '$', style: 'short' } })],
+ })
+ const yAxis = config.yAxis as YAxisConfig
+ // Same path the tooltip uses, so ticks and tooltip read identically.
+ expect(yAxis.tickFormatter?.(1200)).toBe(`$${compactNumber(1200)}`)
+ expect(yAxis.startAtZero).toBe(true)
+ })
+
+ it.each([
+ ['honors an explicit startAtZero=false', { leftYAxisSettings: { startAtZero: false } }, false],
+ ['falls back to the deprecated yAxisAtZero', { yAxisAtZero: false }, false],
+ ])('%s on the left axis', (_name, chartSettings, expected) => {
+ const config = buildLineChartConfig({ xData: dateXData, chartSettings, timezone: 'UTC' })
+ expect((config.yAxis as YAxisConfig).startAtZero).toBe(expected)
+ })
+
+ it('leaves startAtZero unset on a logarithmic axis (no zero baseline to drop)', () => {
+ const config = buildLineChartConfig({
+ xData: dateXData,
+ chartSettings: { leftYAxisSettings: { scale: 'logarithmic' } },
+ timezone: 'UTC',
+ })
+ expect((config.yAxis as YAxisConfig).startAtZero).toBeUndefined()
+ })
+
it.each([
['shows', true, true],
['hides', false, false],
@@ -577,6 +656,28 @@ describe('sqlLineGraphAdapter', () => {
expect(config.yAxis?.scale).toBe('linear')
})
+ it('formats y-axis ticks with the first series column settings for plain bars', () => {
+ const config = buildBarChartConfig({
+ xData: dateXData,
+ chartSettings: {},
+ timezone: 'UTC',
+ visualizationType: ChartDisplayType.ActionsBar,
+ ySeriesData: [ySeries('revenue', [1200], { formatting: { prefix: '$' } })],
+ })
+ expect(config.yAxis?.tickFormatter?.(1200)).toBe('$1200')
+ })
+
+ it('skips the column tick formatter for percent-stacked bars (the axis is 0–100%)', () => {
+ const config = buildBarChartConfig({
+ xData: dateXData,
+ chartSettings: { stackBars100: true },
+ timezone: 'UTC',
+ visualizationType: ChartDisplayType.ActionsStackedBar,
+ ySeriesData: [ySeries('revenue', [1200], { formatting: { prefix: '$' } })],
+ })
+ expect(config.yAxis?.tickFormatter).toBeUndefined()
+ })
+
it('never emits trend lines (quill bar charts have no trend-line support)', () => {
const ySeriesData = [ySeries('a', [1, 2], { display: { trendLine: true } })]
const config = buildBarChartConfig({
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
index 133a880cafe7..4c0145e4d380 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -247,6 +247,31 @@ export function formatSqlSeriesValue(value: number, settings?: AxisSeriesSetting
return String(formatDataWithSettings(value, settings) ?? value)
}
+const isRightAxisSeries = (series: SqlLineYSeries): boolean => series.settings?.display?.yAxisPosition === 'right'
+
+/** Series assigned to a given gutter — tick formatting reads the first series on that axis, so each
+ * gutter formats from a column actually on it rather than a blind `series[0]`. */
+const seriesForAxis = (
+ ySeriesData: SqlLineYSeries[] | null | undefined,
+ position: 'left' | 'right'
+): SqlLineYSeries[] => (ySeriesData ?? []).filter((series) => isRightAxisSeries(series) === (position === 'right'))
+
+/** True when a column carries formatting that should override quill's default numeric axis ticks —
+ * a non-default `style`, a prefix/suffix, or an explicit decimal-place count. Default settings fall
+ * through so the axis keeps quill's human-friendly auto-formatting. */
+export function hasAxisTickFormatting(settings?: AxisSeriesSettings): boolean {
+ const formatting = settings?.formatting
+ if (!formatting) {
+ return false
+ }
+ return (
+ (formatting.style != null && formatting.style !== 'none') ||
+ !!formatting.prefix ||
+ !!formatting.suffix ||
+ formatting.decimalPlaces != null
+ )
+}
+
/** Built-in tooltip for the line + combo SQL charts: each row formatted by its column's settings
* (from `series.meta`), plus an optional total row. */
export function buildSqlTooltipConfig(
@@ -286,17 +311,36 @@ function buildXAxisConfig(xData: AxisSeries<string>, chartSettings: ChartSetting
}
}
+/**
+ * One y-axis config from its `YAxisSettings` plus the series on that axis. Tick formatting reads the
+ * first series on the gutter (the same per-column settings the tooltip uses), and "start at zero"
+ * follows legacy: a linear axis begins at 0 unless explicitly turned off (`yAxisAtZero` fallback).
+ * Percent-stacked bars (`forceLinear`) skip both — the axis shows a 0–100% scale, not column values.
+ */
function buildYAxisConfig(
yAxis: YAxisSettings | undefined,
+ axisSeries: SqlLineYSeries[],
+ yAxisAtZero: boolean | undefined,
{ forceLinear = false, id, position }: { forceLinear?: boolean; id?: string; position?: 'left' | 'right' } = {}
): YAxisConfig {
+ const isLog = !forceLinear && yAxis?.scale === 'logarithmic'
+ const tickSettings = axisSeries[0]?.settings
+ const tickFormatter =
+ !forceLinear && hasAxisTickFormatting(tickSettings)
+ ? (value: number): string => formatSqlSeriesValue(value, tickSettings)
+ : undefined
+
return {
...(id ? { id } : {}),
...(position ? { position } : {}),
label: yAxis?.label,
- scale: !forceLinear && yAxis?.scale === 'logarithmic' ? 'log' : 'linear',
+ scale: isLog ? 'log' : 'linear',
showGrid: yAxis?.showGridLines ?? true,
hide: yAxis?.showTicks === false,
+ tickFormatter,
+ // Quill ignores startAtZero on a log scale; floatBaseline (the false case) is line-only, so
+ // bars/combo keep their zero baseline regardless.
+ startAtZero: forceLinear || !isLog ? (yAxis?.startAtZero ?? yAxisAtZero ?? true) : undefined,
}
}
@@ -311,19 +355,27 @@ export function buildLineChartConfig({
goalLines,
ySeriesData,
}: BuildConfigArgs): TimeSeriesLineChartConfig {
- const hasRightAxisSeries =
- ySeriesData?.some((series) => series.settings?.display?.yAxisPosition === 'right') ?? false
+ const leftSeries = seriesForAxis(ySeriesData, 'left')
+ const rightSeries = seriesForAxis(ySeriesData, 'right')
return {
xAxis: buildXAxisConfig(xData, chartSettings, timezone),
// Emit a per-axis array only when a series actually targets the right axis — otherwise keep
- // the single-object form so single-axis charts render unchanged.
- yAxis: hasRightAxisSeries
- ? [
- buildYAxisConfig(chartSettings.leftYAxisSettings, { id: 'left', position: 'left' }),
- buildYAxisConfig(chartSettings.rightYAxisSettings, { id: 'right', position: 'right' }),
- ]
- : buildYAxisConfig(chartSettings.leftYAxisSettings),
+ // the single-object form so single-axis charts render unchanged. Each gutter formats and
+ // starts-at-zero from a column on that axis.
+ yAxis:
+ rightSeries.length > 0
+ ? [
+ buildYAxisConfig(chartSettings.leftYAxisSettings, leftSeries, chartSettings.yAxisAtZero, {
+ id: 'left',
+ position: 'left',
+ }),
+ buildYAxisConfig(chartSettings.rightYAxisSettings, rightSeries, chartSettings.yAxisAtZero, {
+ id: 'right',
+ position: 'right',
+ }),
+ ]
+ : buildYAxisConfig(chartSettings.leftYAxisSettings, leftSeries, chartSettings.yAxisAtZero),
goalLines: schemaGoalLinesToConfigs(goalLines),
trendLines: buildTrendLineConfigs(ySeriesData),
legend: buildLegendConfig(chartSettings),
@@ -337,12 +389,20 @@ export function buildBarChartConfig({
timezone,
goalLines,
visualizationType,
+ ySeriesData,
}: BuildBarConfigArgs): TimeSeriesBarChartConfig {
const barLayout = barLayoutForDisplay(visualizationType, chartSettings)
return {
xAxis: buildXAxisConfig(xData, chartSettings, timezone),
- yAxis: buildYAxisConfig(chartSettings.leftYAxisSettings, { forceLinear: barLayout === 'percent' }),
+ yAxis: buildYAxisConfig(
+ chartSettings.leftYAxisSettings,
+ seriesForAxis(ySeriesData, 'left'),
+ chartSettings.yAxisAtZero,
+ {
+ forceLinear: barLayout === 'percent',
+ }
+ ),
goalLines: schemaGoalLinesToConfigs(goalLines),
barLayout,
legend: buildLegendConfig(chartSettings),
@@ -360,7 +420,11 @@ export function buildComboChartConfig({
}: BuildBarConfigArgs): TimeSeriesComboChartConfig {
return {
xAxis: buildXAxisConfig(xData, chartSettings, timezone),
- yAxis: buildYAxisConfig(chartSettings.leftYAxisSettings),
+ yAxis: buildYAxisConfig(
+ chartSettings.leftYAxisSettings,
+ seriesForAxis(ySeriesData, 'left'),
+ chartSettings.yAxisAtZero
+ ),
goalLines: schemaGoalLinesToConfigs(goalLines),
barLayout: comboBarLayoutForDisplay(visualizationType),
legend: buildLegendConfig(chartSettings),
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 65c6b3065570..2348ea7757d0 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -77,6 +77,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`. `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point).
- `TimeSeriesComboChart` wraps `ComboChart` the way `TimeSeriesLineChart`/`TimeSeriesBarChart` wrap their base charts: `config.xAxis`/`config.yAxis` (date tick formatter, y-format, scale, grid), `config.goalLines` (off-scale targets stretch the value axis via `ComboChart`'s `valueDomain`), `config.legend` (click-to-toggle), and `config.valueLabels`. Per-series `type` (`'bar' | 'line' | 'area'`) drives rendering; `barLayout` (`'stacked' | 'grouped'`) and right-axis series (`yAxisId: 'right'`) carry over from `ComboChart`. `ComboChart` itself now also honors `valueDomain` (primary axis only) and `showAxisLines`.
- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.
+- y-axis baseline: defaults to clamping a non-negative axis down to 0 (matching the classic insight axis). To float the axis to its data range instead — zooming in on the variation — set `yAxis.startAtZero: false` on `TimeSeriesLineChart`, or `config.floatBaseline: true` on the lower-level `LineChart`. Ignored on a log scale (no zero baseline) and applied to the primary axis only. Bar charts always draw from a zero baseline, so the flag is a no-op there.
- Dual / multi y-axis: give a series a `yAxisId` to scale it against a second axis. On `TimeSeriesLineChart`, pass `config.yAxis` as an **array** — one `YAxisConfig` per axis — to format/scale each axis independently: set `id` (matches `Series.yAxisId`; first entry defaults to `'left'`), `position` (`'left'`/`'right'`; first entry defaults to `'left'`, the rest to `'right'`), and the usual `scale`/`format`/`tickFormatter`/`label`/`showGrid` per entry. A single object stays single-axis (unchanged). The second axis only renders when a series actually targets it; the primary (left) axis owns the gridlines. `TimeSeriesBarChart`/`ComboChart` already render per-`yAxisId` axes but share one tick formatter across gutters.
- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis.
diff --git a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
index 85ee54709e6a..c85624fa7738 100644
--- a/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/LineChart/LineChart.tsx
@@ -79,6 +79,7 @@ function LineChartInner<Meta = unknown>({
showGrid = false,
showAxisLines = false,
valueDomain,
+ floatBaseline = false,
yAxes,
} = config ?? {}
@@ -128,6 +129,7 @@ function LineChartInner<Meta = unknown>({
scaleType: yScaleType,
percentStack: percentStackView,
valueDomain,
+ floatBaseline,
axes: yAxes,
})
@@ -151,7 +153,7 @@ function LineChartInner<Meta = unknown>({
_private: lineChartPrivate,
}
},
- [yScaleType, percentStackView, stackedData, valueDomain, yAxes]
+ [yScaleType, percentStackView, stackedData, valueDomain, floatBaseline, yAxes]
)
const drawStatic = useCallback(
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
index 51ed6aab8b63..4990ceec4c03 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.stories.tsx
@@ -215,6 +215,26 @@ export const YAxisFormats: Story = {
),
}
+/** Offset, all-positive series: clamping leaves a tall empty gutter below the data; floating zooms
+ * onto the band so the day-to-day variation is legible. */
+const OFFSET_SERIES: Series[] = [{ key: 'latency', label: 'p95 latency', data: [820, 860, 840, 905, 880, 930, 910] }]
+
+/** `startAtZero` controls the baseline: the default (left) clamps a non-negative axis to 0; setting
+ * it `false` (right) floats the axis to the data range. */
+export const StartAtZero: Story = {
+ render: () => (
+ // eslint-disable-next-line react/forbid-dom-props
+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, auto)', gap: 24 }}>
+ <YFormatCell title="default (clamped to 0)" series={OFFSET_SERIES} config={{ suffix: ' ms' }} />
+ <YFormatCell
+ title="startAtZero: false (floated)"
+ series={OFFSET_SERIES}
+ config={{ suffix: ' ms', startAtZero: false }}
+ />
+ </div>
+ ),
+}
+
const DERIVED_SERIES: Series[] = [
{ key: 'visits', label: 'Visits', data: [20, 35, 28, 60, 45, 70, 52] },
{ key: 'signups', label: 'Sign-ups', data: [4, 8, 6, 14, 11, 19, 13] },
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
index e112170e075a..92a40afa195a 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.test.tsx
@@ -145,6 +145,49 @@ describe('TimeSeriesLineChart', () => {
})
})
+ describe('config.yAxis startAtZero', () => {
+ // An offset, all-positive series: clamping to 0 leaves a big empty gutter below the data,
+ // while floating zooms the axis onto the 50–70 band — so the lowest tick distinguishes them.
+ const OFFSET_SERIES: Series[] = [{ key: 'a', label: 'A', data: [50, 60, 70] }]
+ const lowestTick = (chart: ReturnType<typeof renderHogChart>['chart']): number =>
+ Math.min(...chart.yTicks().map((t) => parseFloat(t.replace(/[^0-9.eE+-]/g, ''))))
+
+ it.each([
+ ['by default', undefined],
+ ['when startAtZero is true', { yAxis: { startAtZero: true } }],
+ ])('clamps the baseline to 0 %s', (_name, config) => {
+ const { chart } = renderHogChart(
+ <TimeSeriesLineChart series={OFFSET_SERIES} labels={LABELS} theme={THEME} config={config} />
+ )
+ expect(lowestTick(chart)).toBe(0)
+ })
+
+ it('floats the axis to the data range when startAtZero is false', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesLineChart
+ series={OFFSET_SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ yAxis: { startAtZero: false } }}
+ />
+ )
+ expect(lowestTick(chart)).toBeGreaterThan(0)
+ })
+
+ it('ignores startAtZero=false on a log scale, where there is no zero baseline to drop', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesLineChart
+ series={OFFSET_SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ yAxis: { startAtZero: false, scale: 'log' } }}
+ />
+ )
+ // A log axis can't include 0 regardless; this just guards against a crash / NaN domain.
+ expect(lowestTick(chart)).toBeGreaterThan(0)
+ })
+ })
+
describe('config.yAxis array (dual y-axis)', () => {
const LEFT_RIGHT_SERIES: Series[] = [
{ key: 'rev', label: 'Revenue', data: [1000, 1500, 1200] },
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index 821c420d52cb..9255966f871f 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -145,6 +145,10 @@ export function TimeSeriesLineChart<Meta = unknown>({
// object stays referentially stable and doesn't re-trigger scale recomputation each render.
const valueDomain = useMemo(() => goalLineValueDomain(referenceLines), [referenceLines])
+ // `startAtZero === false` floats the primary axis to its data range; the default (undefined/true)
+ // keeps the baseline clamped to 0. A log scale has no zero baseline to clamp, so it's a no-op there.
+ const floatBaseline = primaryYAxis?.startAtZero === false && primaryYAxis?.scale !== 'log'
+
const lineChartConfig: LineChartConfig = {
yScaleType: primaryYAxis?.scale,
xTickFormatter,
@@ -159,6 +163,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
showCrosshair,
tooltip: tooltipConfig,
valueDomain,
+ floatBaseline,
yAxes,
}
diff --git a/packages/quill/packages/charts/src/core/scales.test.ts b/packages/quill/packages/charts/src/core/scales.test.ts
index 066323abdb7d..3236925001e6 100644
--- a/packages/quill/packages/charts/src/core/scales.test.ts
+++ b/packages/quill/packages/charts/src/core/scales.test.ts
@@ -79,6 +79,20 @@ describe('hog-charts scales', () => {
expect(domainMin).toBeLessThan(0)
})
+ it('floats the baseline to the data range when floatBaseline is set', () => {
+ const series = [makeSeries({ key: 's1', data: [50, 60, 70] })]
+ const [domainMin] = createYScale(series, dimensions, { floatBaseline: true }).domain()
+ // Without floatBaseline this would clamp to 0; floated, the floor tracks the data minimum.
+ expect(domainMin).toBeGreaterThan(0)
+ expect(domainMin).toBeLessThanOrEqual(50)
+ })
+
+ it('ignores floatBaseline on a log scale (no zero baseline to drop)', () => {
+ const series = [makeSeries({ key: 's1', data: [50, 60, 70] })]
+ const [domainMin] = createYScale(series, dimensions, { floatBaseline: true, scaleType: 'log' }).domain()
+ expect(domainMin).toBeGreaterThan(0)
+ })
+
it('extends max to 0 when all values are negative (mirror of positive-data zero baseline)', () => {
const series = [makeSeries({ key: 's1', data: [-30, -20, -10] })]
const scale = createYScale(series, dimensions)
diff --git a/packages/quill/packages/charts/src/core/scales.ts b/packages/quill/packages/charts/src/core/scales.ts
index 98c3a44758e9..3475d083cc49 100644
--- a/packages/quill/packages/charts/src/core/scales.ts
+++ b/packages/quill/packages/charts/src/core/scales.ts
@@ -137,9 +137,11 @@ export function createYScale(
percentStack?: boolean
/** Fixed `[min, max]` or `{ include }` extra values the domain must cover. */
valueDomain?: ValueDomain
+ /** Float the axis to its data range instead of clamping the baseline to 0. See {@link buildValueScale}. */
+ floatBaseline?: boolean
} = {}
): ScaleLinear<number, number> | ScaleLogarithmic<number, number> {
- const { scaleType = 'linear', percentStack = false, valueDomain } = options
+ const { scaleType = 'linear', percentStack = false, valueDomain, floatBaseline = false } = options
const { fixed, include } = resolveValueDomain(valueDomain)
const tickCount = yTickCountForHeight(dimensions.plotHeight)
@@ -170,6 +172,7 @@ export function createYScale(
tickCount,
scaleType,
allowNegativeBaseline: hasExplicitNegativeGoal,
+ floatBaseline,
})
}
@@ -190,6 +193,9 @@ export function buildValueScale(options: {
primaryRange?: SeriesValueRange
/** Keep a negative min even when the primary data is non-negative (an explicit negative goal). */
allowNegativeBaseline?: boolean
+ /** Skip the zero-baseline clamp entirely so the axis floats to its data range (a y-axis "start at
+ * zero = off"). The default clamps a non-negative axis down to 0. Has no effect on a log scale. */
+ floatBaseline?: boolean
}): D3YScale {
const {
range,
@@ -198,6 +204,7 @@ export function buildValueScale(options: {
scaleType = 'linear',
primaryRange = range,
allowNegativeBaseline = false,
+ floatBaseline = false,
} = options
if (range.count === 0) {
@@ -221,10 +228,12 @@ export function buildValueScale(options: {
return scaleLog().domain(niceLogDomain(range.minPositive, max)).range(valueRange).clamp(true)
}
- if (primaryRange.count > 0 && primaryRange.min >= 0 && !allowNegativeBaseline) {
- min = 0
- } else if (max < 0) {
- max = 0
+ if (!floatBaseline) {
+ if (primaryRange.count > 0 && primaryRange.min >= 0 && !allowNegativeBaseline) {
+ min = 0
+ } else if (max < 0) {
+ max = 0
+ }
}
// The range can collapse to a single point (e.g. all-equal data, or `include`-only goal values
@@ -320,6 +329,9 @@ export function createScales(
* `position` win; otherwise it falls back to `options.scaleType` and the alternating-side
* default from {@link orderedAxisPositions}. */
axes?: { id: string; position?: 'left' | 'right'; scaleType?: 'linear' | 'log' }[]
+ /** Float the primary axis to its data range instead of clamping the baseline to 0. Applied to
+ * the primary axis only, like `valueDomain`. See {@link buildValueScale}. */
+ floatBaseline?: boolean
} = {}
): ScaleSet {
const x = createXScale(labels, dimensions)
@@ -334,6 +346,7 @@ export function createScales(
scaleType: axisOverrides.get(soleAxisId)?.scaleType ?? options.scaleType,
percentStack: options.percentStack,
valueDomain: options.valueDomain,
+ floatBaseline: options.floatBaseline,
})
return { x, y }
}
@@ -346,6 +359,7 @@ export function createScales(
scaleType: override?.scaleType ?? options.scaleType,
percentStack: options.percentStack,
valueDomain: axisIndex === 0 ? options.valueDomain : undefined,
+ floatBaseline: axisIndex === 0 ? options.floatBaseline : undefined,
})
yAxes[axisId] = { scale, position: override?.position ?? position }
})
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index 1cd657033c27..92d51d3eee8c 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -386,6 +386,9 @@ export interface LineChartConfig extends ChartConfig {
percentStackView?: boolean
/** Value-axis domain control — omit for data-derived auto-scaling. See {@link ValueDomain}. */
valueDomain?: ValueDomain
+ /** Float the value axis to its data range instead of clamping the baseline to 0 (a y-axis "start
+ * at zero = off"). Applied to the primary axis only; ignored on a log scale. Defaults to false. */
+ floatBaseline?: boolean
/** Built-in legend with click-to-toggle series visibility. Hidden by default. */
legend?: ChartLegendConfig
}
diff --git a/packages/quill/packages/charts/src/utils/use-axis-formatters.ts b/packages/quill/packages/charts/src/utils/use-axis-formatters.ts
index 15783252abd9..feb7ee80eedb 100644
--- a/packages/quill/packages/charts/src/utils/use-axis-formatters.ts
+++ b/packages/quill/packages/charts/src/utils/use-axis-formatters.ts
@@ -30,6 +30,10 @@ export interface YAxisConfig extends YFormatterConfig {
tickFormatter?: (value: number) => string
hide?: boolean
showGrid?: boolean
+ /** Y-axis baseline behavior. The default (`undefined`/`true`) clamps a non-negative axis down to
+ * 0. Set `false` to float the axis to its data range instead (zoom in on the variation). Ignored
+ * on a log scale, and only honored for the primary axis in the array (multi-axis) form. */
+ startAtZero?: boolean
}
export function useXTickFormatter(
@@ -126,7 +130,8 @@ export function useYTickFormatter(yAxis: YAxisConfig | undefined): ((value: numb
// unrelated config-identity changes — the same field set forms the dependency array.
const { tickFormatter, format, prefix, suffix, decimalPlaces, minDecimalPlaces, currency } = yAxis ?? {}
return useMemo(
- () => resolveYTickFormatter({ tickFormatter, format, prefix, suffix, decimalPlaces, minDecimalPlaces, currency }),
+ () =>
+ resolveYTickFormatter({ tickFormatter, format, prefix, suffix, decimalPlaces, minDecimalPlaces, currency }),
[tickFormatter, format, prefix, suffix, decimalPlaces, minDecimalPlaces, currency]
)
}