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.

fix(insights): rotate SQL bar chart labels (#78238)

Georges-Antoine Assi2f7acaa4fdfc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 0d72ac22cfb5..4b447339d7ac 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -976,6 +976,10 @@ snapshots:
hash: v1.k794b7964.3f142f3d58f1bbcab86f0e1acdd41786fb469fdfc199808ed1c39c3539c59b5d.IPQnKR7_vDrRDZ_MQTgUjHmkQHo5yHbAGC5RULADyjU
components-hogcharts-timeseriesbarchart--percent--light:
hash: v1.k794b7964.19f53e3f52d7ddc1e43240e6213988f5342787070babed3caf6a110d07530e5a.Uhf_1MLcQlajd8yI6X-7Vx1Etxgn3kriO_6rEk3A4QI
+ components-hogcharts-timeseriesbarchart--rotated-category-labels--dark:
+ hash: v1.k794b7964.f9ac04508b6df5c244d02a406064ee25f40f06f5ab43eb2a6b464d30ddd79298.eY2Bdmyb-wHz5OPrmlQjYNEhXeOt4cHot8IWhaoTiiU
+ components-hogcharts-timeseriesbarchart--rotated-category-labels--light:
+ hash: v1.k794b7964.e27e3c48c148543b6b2798edfcf774b95f35b431d1fdbb83fd31ac02f6c71181.yHeh-4hP543v8U_jPcBu1cqAyczvAkFGWaaZzI8Pq_M
components-hogcharts-timeseriesbarchart--y-axis-formats--dark:
hash: v1.k794b7964.edc0c5c8e2544bbebab52216eeedb5bece493a4b876b86487196840c5e64c078.jteMejoEKM8MzoUriksZBrmLOaLnrhgwtP_gJwvH_IA
components-hogcharts-timeseriesbarchart--y-axis-formats--light:
@@ -2841,17 +2845,17 @@ snapshots:
insights-retentionlinechart--realistic-curve--light:
hash: v1.k794b7964.3e4141c2a16b3e2f47465433ef4a4c6465000255c97faec25f458a8c01fb8253.AVEwr4UWiTybgaqLQRr5pWoH814DvMPZPQ7UTz2XKAQ
insights-sqlbargraph--grouped-bar-with-negative-values--dark:
- hash: v1.k794b7964.ecee7d5a4a5cc7d6e545b539a67dac40cd9be1c198efa93d17d527fb0b96dbd6.GgK7DvhnRAi5Q90QJfTEeRxnOqoGFjRXZ7IzbpFiOr4
+ hash: v1.k794b7964.283bee4c2dac75105174851eeb9a1fed0c9ca3d2205d786aafa39865a3fd8938.TeLLwxc-mWGsntqHxicMgtiRmsQjwaf4dDWUCLV1DO0
insights-sqlbargraph--grouped-bar-with-negative-values--light:
- hash: v1.k794b7964.e523f415fb85ef87e597c4156d08d465d4081c30adddd762c0207b80da4405df.YkwjWpaKy0rAF9BHRqe0hWJaFJnpPsKNvRlPQ5Ouq80
+ hash: v1.k794b7964.f650a19c898a1b45659a824ca56b78b832d3229e15216e775abf225c39fc76b7.0GEkJRi-qzoYtdTtlPgeJD1FLrEu4N19aOMCQ3eMdoA
insights-sqlbargraph--stacked-bar--dark:
- hash: v1.k794b7964.efdb0246621af3e4c4c00a04b3aefddbfd99019eeaed7893a5e687588b8d79e2.XosPwBChcHue5QYB5MURLwCmRm2DUm7IpWlcFdvS5eE
+ hash: v1.k794b7964.a45a9739957d0f9c5cb6159c17e23ed65d9264ba32351c15bccab429d5220155.f6ESGa5-PChPxWgHwSnCIGRPGxBSyIMkhZeR7DRVYjQ
insights-sqlbargraph--stacked-bar--light:
- hash: v1.k794b7964.6510ebd0651b076491307d4ee030317d8e287685583337b52f6b3646127ad9ec.obCWaq6I2F-rDziMyVZKZHHSHnGTivHnJtgnrIsRAR0
+ hash: v1.k794b7964.8d28e015206bd7370f1c78539f4e3aac265d28343ebea07514d541cebed112a8.hxrbzRFRPvexTuluONzSog2NGfd3aoRCKmwIprzP0nc
insights-sqlbargraph--stacked-bar-with-negative-values--dark:
- hash: v1.k794b7964.e25ef0a2a09d483c79ab891fec794c082388309da6a82a706f56a03350079b8e.e3LemBPYLJOUAaiVykrWeCeRNvimnjk98wyku3ncjBk
+ hash: v1.k794b7964.41a485724417c895fc08146a5f10648c76af2931f83b1113697017682c80835d.7bQIt1cXr2Nj8lu___2y9bKraj9zeYbtEGjg70mZcz0
insights-sqlbargraph--stacked-bar-with-negative-values--light:
- hash: v1.k794b7964.c9d8a986912632d1cd7ccbec987628ae5d8c3437cdc64e503f7ea6087acec3f3.skBe-MAKvRq9FmUDD9WiW67MaZ0F5fVXnBxPepnOWPM
+ hash: v1.k794b7964.e9f32e35e60194c76df1aad0e7963ca99bc76d2b6099437c5e679c4959feb976.3DeROLuvQPwEHmWPIxoY7SxfXAcAgX6gufInnDLnBh0
insights-sqlpiegraph--breakdown-colors--dark:
hash: v1.k794b7964.459b2f2dad813b806560c40f292c41503482dcc864756aa5c27e936ef6ad5890.35VUrVQBDx9LxDWhN1L1896BV62m-OhK3d4ujQHrU5o
insights-sqlpiegraph--breakdown-colors--light:
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 b29ee9d6c285..8680b5cf7a5d 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.test.ts
@@ -594,6 +594,7 @@ describe('sqlLineGraphAdapter', () => {
it('omits the tick formatter for non-date axes', () => {
const config = buildLineChartConfig({ xData: stringXData, chartSettings: {}, timezone: 'UTC' })
expect(config.xAxis?.tickFormatter).toBeUndefined()
+ expect(config.xAxis?.tickLabelRotation).toBeUndefined()
})
it('maps logarithmic scale and y-axis settings', () => {
@@ -770,6 +771,34 @@ describe('sqlLineGraphAdapter', () => {
column: { name: 'day', type: { name: 'DATE', isNumerical: false }, label: 'day', dataIndex: 0 },
data: ['2024-01-01', '2024-01-02'],
}
+ const datetimeXData: AxisSeries<string> = {
+ column: {
+ name: 'timestamp',
+ type: { name: 'DATETIME', isNumerical: false },
+ label: 'timestamp',
+ dataIndex: 0,
+ },
+ data: ['2024-01-01T00:00:00Z', '2024-01-02T00:00:00Z'],
+ }
+ const stringXData: AxisSeries<string> = {
+ column: { name: 'path', type: { name: 'STRING', isNumerical: false }, label: 'path', dataIndex: 0 },
+ data: ['/api/projects/alpha', '/api/projects/beta'],
+ }
+
+ it.each([
+ ['non-date', stringXData, -45],
+ ['date', dateXData, undefined],
+ ['datetime', datetimeXData, undefined],
+ ])('sets fixed tick rotation only for %s category axes', (_name, xData, expected) => {
+ const config = buildBarChartConfig({
+ xData,
+ chartSettings: {},
+ timezone: 'UTC',
+ visualizationType: ChartDisplayType.ActionsBar,
+ })
+
+ expect(config.xAxis?.tickLabelRotation).toBe(expected)
+ })
it('forces a linear y-axis scale for percent-stacked bars', () => {
const chartSettings: ChartSettings = {
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
index 1570fcd14e75..a70de12fd6f6 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -317,12 +317,20 @@ export interface BuildBarConfigArgs extends BuildConfigArgs {
visualizationType: ChartDisplayType
}
-function buildXAxisConfig(xData: AxisSeries<string>, chartSettings: ChartSettings, timezone: string): XAxisConfig {
+const SQL_BAR_TICK_LABEL_ROTATION = -45
+
+function buildXAxisConfig(
+ xData: AxisSeries<string>,
+ chartSettings: ChartSettings,
+ timezone: string,
+ tickLabelRotation?: number
+): XAxisConfig {
const isDateAxis = xData.column.type.name === 'DATE' || xData.column.type.name === 'DATETIME'
return {
label: chartSettings.xAxisLabel,
tickFormatter: isDateAxis ? createXAxisTickCallback({ allDays: xData.data, timezone }) : undefined,
+ tickLabelRotation: isDateAxis ? undefined : tickLabelRotation,
hide: chartSettings.showXAxisTicks === false,
}
}
@@ -448,7 +456,7 @@ export function buildBarChartConfig({
const rightSeries = seriesForAxis(ySeriesData, 'right')
return {
- xAxis: buildXAxisConfig(xData, chartSettings, timezone),
+ xAxis: buildXAxisConfig(xData, chartSettings, timezone, SQL_BAR_TICK_LABEL_ROTATION),
yAxis:
rightSeries.length > 0
? [
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index 6418cde97eb3..27acbaaf4840 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -94,6 +94,7 @@ Safari is the exception: it never fires `contextrestored`, so a context lost the
- The composable form of `MetricCard` lives one layer up as `Metric` in `@posthog/quill-components` (it needs `Card`/`Badge` from primitives, which charts can't depend on). It's built on `Sparkline` plus the headless metric helpers this package exports — `resolveDelta` / `computeFallbackChangePercent` (delta math), `useAnimatedNumber` (count-up headline), `useHoverIntent` (hover dwell) — and the `MetricChange` / `ResolvedDelta` types. Reach for `Metric` when you need a custom layout; use the monolithic `MetricCard` here for the default self-contained tile.
- `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' | 'percent'`), `divergingStack` (stacked only — negative bar values stack below the zero baseline instead of being clamped to 0, same semantics as `BarsConfig.divergingStack`), 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 | duration_ns`, plus `prefix`/`suffix`. Numeric and percentage ticks default to two decimals but gain a decimal per leading zero below 0.1, so a small-valued axis (say latency in seconds over 0–0.012) doesn't render every tick as `0.01`; `decimalPlaces` pins the precision instead.
+- Fixed x-axis tick rotation: set `xAxis.tickLabelRotation` on a time-series chart (`-45` tilts labels left). Values are clamped to `-90..90`; omit it to keep horizontal labels and existing collision behavior.
- 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. Duration formatters accept seconds (`duration`), milliseconds (`duration_ms`), or nanoseconds (`duration_ns`). `hide` and `startAtZero` are honored per entry (bar-series axes keep their zero baseline). 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. More than two axes work too (trends `showMultipleYAxes`): they stack outward per side and alternate sides. Each entry's `label` renders that axis's title at its own gutter — every axis is titled the same way (a single-object `yAxis`/scalar `yAxisLabel` is just the one left axis), driven by the shared `computeYAxisGutters` layout that `AxisLabels` (ticks) and `AxisTitles` (titles) both read so the two can't drift. `TimeSeriesBarChart`/`TimeSeriesComboChart` take the same `yAxis` array; a sole axis pinned `right` renders on the right on every chart type.
- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/`BarChart`/`TimeSeriesBarChart`/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. Despite the name it is label-generic — it resolves the drag against label positions, so it works the same on categorical labels (weekdays, duration buckets) as on dates. A drag whose edges both snap to the same label (common on sparse charts, e.g. a 3-bar monthly chart) selects that single bucket, provided the drag spans enough horizontal distance to read as intentional. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis (`axisOrientation: 'horizontal'` bars, where the core disables the gesture).
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx
index bc69f9c17f9c..5ed00a934def 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.stories.tsx
@@ -62,6 +62,29 @@ export const Grouped: Story = {
},
}
+const LONG_CATEGORY_LABELS = [
+ '/api/projects/alpha/insights/daily-active-users',
+ '/api/projects/beta/insights/weekly-retention',
+ '/api/projects/gamma/insights/conversion-funnel',
+]
+const LONG_CATEGORY_SERIES: Series[] = [{ key: 'requests', label: 'Requests', data: [420, 315, 510] }]
+
+export const RotatedCategoryLabels: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ return (
+ <Stage width={720} height={420}>
+ <TimeSeriesBarChart
+ series={LONG_CATEGORY_SERIES}
+ labels={LONG_CATEGORY_LABELS}
+ theme={theme}
+ config={{ xAxis: { tickLabelRotation: -45 }, yAxis: { showGrid: true } }}
+ />
+ </Stage>
+ )
+ },
+}
+
// Grouped bars whose series span very different magnitudes — each is scaled against its own
// y-axis (`yAxisId`) so all three stay individually legible instead of the small series being
// flattened against the large one. Mirrors the legacy "show multiple y-axes" trends option.
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
index f2fc0922b213..234b7d131e26 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.test.tsx
@@ -38,6 +38,21 @@ describe('TimeSeriesBarChart', () => {
expect(chart.xTicks()).toEqual(['tick-0', 'tick-1', 'tick-2'])
})
+ it('rotates rendered ticks when xAxis.tickLabelRotation is set', () => {
+ const { chart } = renderHogChart(
+ <TimeSeriesBarChart
+ series={SERIES}
+ labels={LABELS}
+ theme={THEME}
+ config={{ xAxis: { tickLabelRotation: -45 } }}
+ />
+ )
+ const ticks = chart.element.querySelectorAll<HTMLElement>('[data-attr="hog-chart-axis-tick-x"]')
+
+ expect(ticks.length).toBeGreaterThan(0)
+ expect(Array.from(ticks).every((tick) => tick.style.transform === 'rotate(-45deg)')).toBe(true)
+ })
+
it('builds an auto date formatter from xAxis.timezone + xAxis.interval', () => {
const labels = ['2024-06-10', '2024-06-11', '2024-06-12']
const { chart } = renderHogChart(
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
index f00478a29d70..ad8d2f091dde 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesBarChart/TimeSeriesBarChart.tsx
@@ -139,6 +139,7 @@ export function TimeSeriesBarChart<Meta = unknown>({
margins,
yScaleType: primaryYAxis?.scale,
xTickFormatter,
+ xTickLabelRotation: xAxis?.tickLabelRotation,
yTickFormatter,
hideXAxis: xAxis?.hide,
hideYAxis: yAxes ? yAxes.length > 0 && yAxes.every((a) => a.hide) : primaryYAxis?.hide,
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
index 1b6dd826992c..5f30d469d74d 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesComboChart/TimeSeriesComboChart.tsx
@@ -123,6 +123,7 @@ export function TimeSeriesComboChart<Meta = unknown>({
const comboChartConfig: ComboChartConfig = {
yScaleType: primaryYAxis?.scale,
xTickFormatter,
+ xTickLabelRotation: xAxis?.tickLabelRotation,
yTickFormatter,
hideXAxis: xAxis?.hide,
hideYAxis: yAxes ? yAxes.length > 0 && yAxes.every((a) => a.hide) : primaryYAxis?.hide,
diff --git a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
index a081bc596636..604cd6a8bf19 100644
--- a/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
+++ b/packages/quill/packages/charts/src/charts/TimeSeriesLineChart/TimeSeriesLineChart.tsx
@@ -135,6 +135,7 @@ export function TimeSeriesLineChart<Meta = unknown>({
const lineChartConfig: LineChartConfig = {
yScaleType: primaryYAxis?.scale,
xTickFormatter,
+ xTickLabelRotation: xAxis?.tickLabelRotation,
yTickFormatter,
hideXAxis: xAxis?.hide,
// Multi-axis: each axis hides its own gutter; collapse globally only when all are hidden.
diff --git a/packages/quill/packages/charts/src/core/Chart.tsx b/packages/quill/packages/charts/src/core/Chart.tsx
index bff40866e9ac..17044351630c 100644
--- a/packages/quill/packages/charts/src/core/Chart.tsx
+++ b/packages/quill/packages/charts/src/core/Chart.tsx
@@ -141,6 +141,7 @@ export function Chart<Meta = unknown>({
}: ChartProps<Meta>): React.ReactElement {
const {
xTickFormatter,
+ xTickLabelRotation = 0,
yTickFormatter,
hideXAxis = false,
hideYAxis = false,
@@ -211,6 +212,7 @@ export function Chart<Meta = unknown>({
hideYAxis,
xAxisLabel,
xTickFormatter,
+ xTickLabelRotation,
yTickFormatter,
axisOrientation,
override: marginsOverride,
@@ -283,7 +285,9 @@ export function Chart<Meta = unknown>({
}
const xs = hideXAxis
? []
- : computeVisibleXLabels(labels, scales.x, xTickFormatter, maxCategoryLabelWidth).map((l) => l.x)
+ : computeVisibleXLabels(labels, scales.x, xTickFormatter, maxCategoryLabelWidth, xTickLabelRotation).map(
+ (l) => l.x
+ )
const ys = yGutters.flatMap((gutter) =>
computeVisibleYTicks(gutter.ticks, gutter.scale)
.map((tick) => gutter.scale(tick))
@@ -298,6 +302,7 @@ export function Chart<Meta = unknown>({
axisOrientation,
labels,
xTickFormatter,
+ xTickLabelRotation,
maxCategoryLabelWidth,
yGutters,
hideXAxis,
@@ -437,6 +442,7 @@ export function Chart<Meta = unknown>({
>
<AxisLabels
xTickFormatter={xTickFormatter}
+ xTickLabelRotation={xTickLabelRotation}
yTickFormatter={resolvedYFormatter}
hideXAxis={hideXAxis}
hideYAxis={hideYAxis}
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts
index 8736e2f8372d..54834f0723a2 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.test.ts
@@ -129,6 +129,15 @@ describe('useChartMargins', () => {
expect(render({ series: big }).left).toBeGreaterThan(render({ series: small }).left)
})
+ it('moves rotated category-label space from the horizontal margins to the bottom margin', () => {
+ const longLabels = ['a-very-long-category-label', 'another-long-category-label']
+ const horizontal = render({ labels: longLabels })
+ const rotated = render({ labels: longLabels, xTickLabelRotation: -45 })
+
+ expect(rotated.bottom).toBeGreaterThan(horizontal.bottom)
+ expect(rotated.left + rotated.right).toBeLessThan(horizontal.left + horizontal.right)
+ })
+
describe('horizontal orientation', () => {
it('sizes the left margin from the widest category label, not value-tick width', () => {
const longCategoryLabels = ['shortest', 'a-considerably-longer-label']
diff --git a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
index 7a8148160377..64326ec24030 100644
--- a/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
+++ b/packages/quill/packages/charts/src/core/hooks/useChartMargins.ts
@@ -1,7 +1,12 @@
import { scaleLinear } from 'd3-scale'
import { useMemo } from 'react'
-import { normalizeAxisLabel } from '../../utils/axis-labels'
+import {
+ AXIS_TICK_LABEL_HEIGHT,
+ normalizeAxisLabel,
+ normalizeTickLabelRotation,
+ rotatedTickLabelSize,
+} from '../../utils/axis-labels'
import { measureLabelWidth } from '../../utils/text-measure'
import { autoFormatterFor, orderedAxisPositions, seriesValueRange } from '../scales'
import { DEFAULT_Y_AXIS_ID } from '../types'
@@ -30,6 +35,7 @@ interface UseChartMarginsOptions {
hideYAxis: boolean
xAxisLabel?: string
xTickFormatter?: (value: string, index: number) => string | null
+ xTickLabelRotation?: number
yTickFormatter?: (value: number) => string
axisOrientation?: 'vertical' | 'horizontal'
/** Per-side overrides applied on top of the computed margins. */
@@ -76,20 +82,40 @@ export function applyMarginOverride(
return result
}
-function widestCategoryLabelWidth(
+interface CategoryLabelWidths {
+ first: number
+ last: number
+ widest: number
+}
+
+function categoryLabelWidths(
labels: string[],
xTickFormatter: ((value: string, index: number) => string | null) | undefined,
maxCategoryLabelWidth = 0
-): number {
+): CategoryLabelWidths {
+ // Track first/last/widest in one pass — spreading a per-label array into `Math.max`
+ // can overflow the argument limit on a high-cardinality category axis.
+ let first = 0
+ let last = 0
let widest = 0
+ let seenAny = false
for (let i = 0; i < labels.length; i++) {
const text = xTickFormatter ? xTickFormatter(labels[i], i) : labels[i]
if (text === null) {
continue
}
- widest = Math.max(widest, measureLabelWidth(text))
+ const measured = measureLabelWidth(text)
+ const width = maxCategoryLabelWidth > 0 ? Math.min(measured, maxCategoryLabelWidth) : measured
+ if (!seenAny) {
+ first = width
+ seenAny = true
+ }
+ last = width
+ if (width > widest) {
+ widest = width
+ }
}
- return maxCategoryLabelWidth > 0 ? Math.min(widest, maxCategoryLabelWidth) : widest
+ return { first, last, widest }
}
function widestValueLabelWidth(series: Series[], yTickFormatter: ((value: number) => string) | undefined): number {
@@ -117,6 +143,7 @@ export function useChartMargins({
hideYAxis,
xAxisLabel,
xTickFormatter,
+ xTickLabelRotation = 0,
yTickFormatter,
axisOrientation = 'vertical',
override,
@@ -130,6 +157,11 @@ export function useChartMargins({
const isHorizontal = axisOrientation === 'horizontal'
const valueSeries = valueRangeSeries ?? series
const normalizedXAxisLabel = normalizeAxisLabel(xAxisLabel)
+ const tickLabelRotation = isHorizontal ? 0 : normalizeTickLabelRotation(xTickLabelRotation)
+ const categoryWidths = useMemo(
+ () => categoryLabelWidths(labels, xTickFormatter, maxCategoryLabelWidth),
+ [labels, xTickFormatter, maxCategoryLabelWidth]
+ )
const hasMultipleAxes = useMemo(() => {
const axisIds = new Set(
@@ -174,24 +206,49 @@ export function useChartMargins({
return 0
}
if (isHorizontal) {
- return widestCategoryLabelWidth(labels, xTickFormatter, maxCategoryLabelWidth)
+ return categoryWidths.widest
}
return widestValueLabelWidth(valueSeries, yTickFormatter)
- }, [valueSeries, yTickFormatter, hideYAxis, isHorizontal, labels, xTickFormatter, maxCategoryLabelWidth])
+ }, [valueSeries, yTickFormatter, hideYAxis, isHorizontal, categoryWidths.widest])
- const xLabelHalfWidth = useMemo<number>(() => {
+ const xLabelEdgeReserves = useMemo<{ left: number; right: number }>(() => {
if (hideXAxis) {
- return 0
+ return { left: 0, right: 0 }
}
if (isHorizontal) {
const widest = widestValueLabelWidth(valueSeries, yTickFormatter)
- return Math.ceil(widest / 2)
+ const halfWidth = Math.ceil(widest / 2)
+ return { left: halfWidth, right: halfWidth }
}
if (labels.length === 0) {
+ return { left: 0, right: 0 }
+ }
+ if (tickLabelRotation === 0) {
+ const halfWidth = Math.ceil(categoryWidths.widest / 2)
+ return { left: halfWidth, right: halfWidth }
+ }
+
+ const radians = (Math.abs(tickLabelRotation) * Math.PI) / 180
+ const thinEdgeReserve = Math.ceil(AXIS_TICK_LABEL_HEIGHT * Math.sin(radians))
+ if (tickLabelRotation < 0) {
+ return {
+ left: Math.ceil(categoryWidths.first * Math.cos(radians)),
+ right: thinEdgeReserve,
+ }
+ }
+ return {
+ left: thinEdgeReserve,
+ right: Math.ceil(categoryWidths.last * Math.cos(radians)),
+ }
+ }, [categoryWidths, hideXAxis, isHorizontal, labels.length, tickLabelRotation, valueSeries, yTickFormatter])
+
+ const xLabelExtraBottom = useMemo<number>(() => {
+ if (hideXAxis || isHorizontal || tickLabelRotation === 0) {
return 0
}
- return Math.ceil(widestCategoryLabelWidth(labels, xTickFormatter, maxCategoryLabelWidth) / 2)
- }, [labels, xTickFormatter, hideXAxis, isHorizontal, valueSeries, yTickFormatter, maxCategoryLabelWidth])
+ const rotatedHeight = rotatedTickLabelSize(categoryWidths.widest, tickLabelRotation).height
+ return Math.max(0, Math.ceil(rotatedHeight - AXIS_TICK_LABEL_HEIGHT))
+ }, [categoryWidths.widest, hideXAxis, isHorizontal, tickLabelRotation])
// With multiple y-axes the value-axis labels stack into several gutters per side; reserve the
// cumulative width so the outer gutters aren't clipped. Mirrors AxisLabels' gutter layout.
@@ -242,18 +299,18 @@ export function useChartMargins({
return useMemo<ChartMargins>(() => {
const bottom = hideXAxis
? COLLAPSED_AXIS_MARGIN
- : DEFAULT_MARGINS.bottom + (normalizedXAxisLabel ? X_AXIS_TITLE_MARGIN : 0)
+ : DEFAULT_MARGINS.bottom + xLabelExtraBottom + (normalizedXAxisLabel ? X_AXIS_TITLE_MARGIN : 0)
const leftLabelReserve = gutterReserves ? gutterReserves.left : Math.ceil(yLabelWidth) + Y_LABEL_RIGHT_PADDING
const left = hideYAxis
? COLLAPSED_AXIS_MARGIN
: Math.max(
MIN_LEFT_MARGIN,
leftLabelReserve + Y_LABEL_LEFT_GUTTER,
- xLabelHalfWidth + X_LABEL_EDGE_PADDING
+ xLabelEdgeReserves.left + X_LABEL_EDGE_PADDING
) + titleReserve.left
const rightFloor = usesPerSideGutters && !hideYAxis ? MIN_RIGHT_MARGIN_DUAL_AXIS : DEFAULT_MARGINS.right
const rightLabelReserve = (gutterReserves?.right ?? 0) + titleReserve.right
- const right = Math.max(rightFloor, rightLabelReserve, xLabelHalfWidth + X_LABEL_EDGE_PADDING)
+ const right = Math.max(rightFloor, rightLabelReserve, xLabelEdgeReserves.right + X_LABEL_EDGE_PADDING)
const computed: ChartMargins = { top: DEFAULT_MARGINS.top, right, bottom, left }
return override ? applyMarginOverride(computed, override) : computed
// Depend on the individual sides, not `override` by identity — callers are expected to build
@@ -267,7 +324,8 @@ export function useChartMargins({
usesPerSideGutters,
gutterReserves,
yLabelWidth,
- xLabelHalfWidth,
+ xLabelEdgeReserves,
+ xLabelExtraBottom,
normalizedXAxisLabel,
titleReserve,
override?.top,
diff --git a/packages/quill/packages/charts/src/core/types.ts b/packages/quill/packages/charts/src/core/types.ts
index 44dc3b9c7fc5..6f1be6ef2902 100644
--- a/packages/quill/packages/charts/src/core/types.ts
+++ b/packages/quill/packages/charts/src/core/types.ts
@@ -246,6 +246,8 @@ export interface ChartConfig {
/** Custom x-axis tick label formatter. Return null to skip a tick. Called with (label, index). */
xTickFormatter?: (value: string, index: number) => string | null
+ /** Fixed x-axis tick-label rotation in degrees, clamped to -90..90. Defaults to 0. */
+ xTickLabelRotation?: number
/** Custom y-axis tick label formatter. Overrides the built-in auto-precision formatter. */
yTickFormatter?: (value: number) => string
/** Hide the x-axis labels and reduce bottom margin. */
diff --git a/packages/quill/packages/charts/src/overlays/AxisLabels.test.ts b/packages/quill/packages/charts/src/overlays/AxisLabels.test.ts
index 4a1436e791a0..9950c1c06851 100644
--- a/packages/quill/packages/charts/src/overlays/AxisLabels.test.ts
+++ b/packages/quill/packages/charts/src/overlays/AxisLabels.test.ts
@@ -40,6 +40,17 @@ describe('computeVisibleXLabels', () => {
expect(visible.map((v) => v.index)).toEqual([0])
})
+
+ it('keeps more long labels when they are rotated', () => {
+ const labels = ['/api/projects/alpha', '/api/projects/beta', '/api/projects/gamma']
+ const scale = (label: string): number => labels.indexOf(label) * 30
+
+ const horizontal = computeVisibleXLabels(labels, scale)
+ const rotated = computeVisibleXLabels(labels, scale, undefined, 0, -45)
+
+ expect(horizontal.length).toBeLessThan(labels.length)
+ expect(rotated.map((label) => label.text)).toEqual(labels)
+ })
})
describe('computeVisibleValueTicks', () => {
diff --git a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx b/packages/quill/packages/charts/src/overlays/AxisLabels.tsx
index 7f1ee397edf8..c3ebd387c316 100644
--- a/packages/quill/packages/charts/src/overlays/AxisLabels.tsx
+++ b/packages/quill/packages/charts/src/overlays/AxisLabels.tsx
@@ -2,10 +2,12 @@ import React, { useMemo } from 'react'
import { useChartLayout } from '../core/chart-context'
import { TICK_GAP } from '../core/y-axis-gutters'
+import { minimumRotatedTickLabelGap, normalizeTickLabelRotation } from '../utils/axis-labels'
import { AXIS_LABEL_FONT, getTextMeasureCtx, truncateToWidth } from '../utils/text-measure'
interface AxisLabelsProps {
xTickFormatter?: (value: string, index: number) => string | null
+ xTickLabelRotation?: number
yTickFormatter?: (value: number) => string
hideXAxis?: boolean
hideYAxis?: boolean
@@ -46,13 +48,33 @@ function truncateWithTitle(fullText: string, maxCategoryLabelWidth: number): { t
return { text, title: text === fullText ? undefined : fullText }
}
-/** Greedily keep entries left→right, dropping any whose centered label would collide with the
- * previously kept one (closer than `padding` px). Entries must be sorted by ascending `x`. */
-function dropOverlappingLabels<T extends { text: string; x: number }>(candidates: T[], padding: number): T[] {
+/** Greedily keep entries left→right. Horizontal labels use their measured text boxes; rotated
+ * labels use the minimum perpendicular separation between parallel lines of text. */
+function dropOverlappingLabels<T extends { text: string; x: number }>(
+ candidates: T[],
+ padding: number,
+ tickLabelRotation = 0
+): T[] {
if (candidates.length === 0) {
return []
}
+ const rotation = normalizeTickLabelRotation(tickLabelRotation)
+ if (rotation !== 0) {
+ // Perpendicular separation keeps the parallel lines of text from overlapping; `padding`
+ // floors the along-axis spacing so the same caller-provided gap applies as in the flat path.
+ const minimumGap = Math.max(minimumRotatedTickLabelGap(rotation), padding)
+ const visible: T[] = []
+ let lastX = -Infinity
+ for (const candidate of candidates) {
+ if (candidate.x >= lastX + minimumGap) {
+ visible.push(candidate)
+ lastX = candidate.x
+ }
+ }
+ return visible
+ }
+
const ctx = getTextMeasureCtx()
if (!ctx) {
return candidates
@@ -79,7 +101,8 @@ export function computeVisibleXLabels(
labels: string[],
xScale: (label: string) => number | undefined,
formatter?: (value: string, index: number) => string | null,
- maxCategoryLabelWidth = 0
+ maxCategoryLabelWidth = 0,
+ tickLabelRotation = 0
): XLabelCandidate[] {
const candidates: XLabelCandidate[] = []
for (let i = 0; i < labels.length; i++) {
@@ -96,7 +119,7 @@ export function computeVisibleXLabels(
candidates.push({ index: i, text, title, x })
}
- return dropOverlappingLabels(candidates, CATEGORY_LABEL_PADDING)
+ return dropOverlappingLabels(candidates, CATEGORY_LABEL_PADDING, tickLabelRotation)
}
interface ValueTickCandidate {
@@ -239,6 +262,7 @@ function XTickLabel({
color,
dataAttr,
title,
+ tickLabelRotation = 0,
}: {
x: number
box: ChartBox
@@ -246,7 +270,20 @@ function XTickLabel({
color: string
dataAttr: string
title?: string
+ tickLabelRotation?: number
}): React.ReactElement {
+ const rotation = normalizeTickLabelRotation(tickLabelRotation)
+ const positionStyle: React.CSSProperties =
+ rotation < 0
+ ? {
+ right: box.width - x,
+ transform: `rotate(${rotation}deg)`,
+ transformOrigin: 'top right',
+ }
+ : rotation > 0
+ ? { left: x, transform: `rotate(${rotation}deg)`, transformOrigin: 'top left' }
+ : { left: x, transform: 'translateX(-50%)' }
+
return (
<div
data-attr={dataAttr}
@@ -254,9 +291,8 @@ function XTickLabel({
style={{
...TICK_STYLE_BASE,
...titleStyle(title),
- left: x,
+ ...positionStyle,
top: box.plotTop + box.plotHeight + TICK_GAP,
- transform: 'translateX(-50%)',
color,
}}
>
@@ -267,6 +303,7 @@ function XTickLabel({
export const AxisLabels = React.memo(function AxisLabels({
xTickFormatter,
+ xTickLabelRotation = 0,
yTickFormatter,
hideXAxis,
hideYAxis,
@@ -282,8 +319,8 @@ export const AxisLabels = React.memo(function AxisLabels({
() =>
hideXAxis || orientation === 'horizontal'
? []
- : computeVisibleXLabels(labels, scales.x, xTickFormatter, maxCategoryLabelWidth),
- [hideXAxis, labels, scales.x, xTickFormatter, orientation, maxCategoryLabelWidth]
+ : computeVisibleXLabels(labels, scales.x, xTickFormatter, maxCategoryLabelWidth, xTickLabelRotation),
+ [hideXAxis, labels, scales.x, xTickFormatter, xTickLabelRotation, orientation, maxCategoryLabelWidth]
)
// Mirror the vertical branch's memoization so an unrelated prop change (e.g. axisColor)
@@ -368,6 +405,7 @@ export const AxisLabels = React.memo(function AxisLabels({
box={dimensions}
text={text}
title={title}
+ tickLabelRotation={xTickLabelRotation}
color={axisColor}
dataAttr="hog-chart-axis-tick-x"
/>
diff --git a/packages/quill/packages/charts/src/utils/axis-labels.test.ts b/packages/quill/packages/charts/src/utils/axis-labels.test.ts
new file mode 100644
index 000000000000..823d5c921943
--- /dev/null
+++ b/packages/quill/packages/charts/src/utils/axis-labels.test.ts
@@ -0,0 +1,15 @@
+import { normalizeTickLabelRotation } from './axis-labels'
+
+describe('axis label utilities', () => {
+ it.each([
+ ['positive rotation', 45, 45],
+ ['negative rotation', -45, -45],
+ ['positive overflow', 120, 90],
+ ['negative overflow', -120, -90],
+ ['NaN', Number.NaN, 0],
+ ['positive infinity', Number.POSITIVE_INFINITY, 0],
+ ['negative infinity', Number.NEGATIVE_INFINITY, 0],
+ ])('normalizes %s', (_name, rotation, expected) => {
+ expect(normalizeTickLabelRotation(rotation)).toBe(expected)
+ })
+})
diff --git a/packages/quill/packages/charts/src/utils/axis-labels.ts b/packages/quill/packages/charts/src/utils/axis-labels.ts
index 1e5721a182d3..c88b3ae72f56 100644
--- a/packages/quill/packages/charts/src/utils/axis-labels.ts
+++ b/packages/quill/packages/charts/src/utils/axis-labels.ts
@@ -1,4 +1,34 @@
+export const AXIS_TICK_LABEL_HEIGHT = 14
+
+const MAX_TICK_LABEL_ROTATION = 90
+const ROTATED_TICK_LABEL_PADDING = 4
+
export function normalizeAxisLabel(label: string | null | undefined): string | undefined {
const trimmed = label?.trim()
return trimmed ? trimmed : undefined
}
+
+export function normalizeTickLabelRotation(rotation = 0): number {
+ if (!Number.isFinite(rotation)) {
+ return 0
+ }
+ return Math.max(-MAX_TICK_LABEL_ROTATION, Math.min(MAX_TICK_LABEL_ROTATION, rotation))
+}
+
+export function rotatedTickLabelSize(width: number, rotation: number): { width: number; height: number } {
+ const radians = (Math.abs(normalizeTickLabelRotation(rotation)) * Math.PI) / 180
+ const sin = Math.sin(radians)
+ const cos = Math.cos(radians)
+ return {
+ width: width * cos + AXIS_TICK_LABEL_HEIGHT * sin,
+ height: width * sin + AXIS_TICK_LABEL_HEIGHT * cos,
+ }
+}
+
+export function minimumRotatedTickLabelGap(rotation: number): number {
+ const radians = (Math.abs(normalizeTickLabelRotation(rotation)) * Math.PI) / 180
+ if (radians === 0) {
+ return 0
+ }
+ return Math.ceil((AXIS_TICK_LABEL_HEIGHT + ROTATED_TICK_LABEL_PADDING) / Math.sin(radians))
+}
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 a24c61742b56..eedd9d5fc9c2 100644
--- a/packages/quill/packages/charts/src/utils/use-axis-formatters.ts
+++ b/packages/quill/packages/charts/src/utils/use-axis-formatters.ts
@@ -8,6 +8,8 @@ export interface XAxisConfig {
label?: string
/** Explicit tick formatter. When set, it wins over the auto date formatter. */
tickFormatter?: (value: string, index: number) => string | null
+ /** Fixed tick-label rotation in degrees, clamped to -90..90. Negative values tilt left. */
+ tickLabelRotation?: number
hide?: boolean
/** Timezone used when interpreting date labels for the auto date formatter. */
timezone?: string