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): fit horizontal bar charts to dashboard tiles (#61245)

Sam Pennington8f58a3586078
diff --git a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
index aed0c3184f84..7005ed8a47a8 100644
--- a/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
+++ b/frontend/src/lib/hog-charts/charts/BarChart/BarChart.tsx
@@ -169,14 +169,17 @@ function BarChartInner<Meta = unknown>({
maxBandRange,
bandPadding,
minBandSize,
+ fitToHeight = false,
valueDomain,
roundStackEnds = false,
} = config?.bars ?? {}
const isHorizontal = axisOrientation === 'horizontal'
const resolvedMinBandSize = minBandSize ?? (isHorizontal ? HORIZONTAL_MIN_BAND_SIZE_DEFAULT : 0)
+ // Fit-to-height drops overflow rows instead of growing the container, so it never sets a
+ // wrapper floor — the chart fills whatever height the tile gives it.
const wrapperMinHeight = useMemo(() => {
- if (!isHorizontal || resolvedMinBandSize <= 0) {
+ if (!isHorizontal || fitToHeight || resolvedMinBandSize <= 0) {
return undefined
}
const uniqueBands = new Set(labels).size
@@ -184,7 +187,7 @@ function BarChartInner<Meta = unknown>({
return undefined
}
return uniqueBands * resolvedMinBandSize + HORIZONTAL_CHART_MARGIN_PX
- }, [isHorizontal, resolvedMinBandSize, labels])
+ }, [isHorizontal, fitToHeight, resolvedMinBandSize, labels])
const stackedData = useMemo((): Map<string, StackedBand> | undefined => {
if (barLayout === 'percent') {
@@ -256,6 +259,8 @@ function BarChartInner<Meta = unknown>({
stackedSeries,
maxBandRange,
bandPadding,
+ fitToHeight,
+ minBandSize: resolvedMinBandSize,
valueDomain,
})
@@ -315,6 +320,8 @@ function BarChartInner<Meta = unknown>({
divergingStack,
maxBandRange,
bandPadding,
+ fitToHeight,
+ resolvedMinBandSize,
valueDomain,
]
)
diff --git a/frontend/src/lib/hog-charts/core/scales.test.ts b/frontend/src/lib/hog-charts/core/scales.test.ts
index 6c7344aed860..913820184abb 100644
--- a/frontend/src/lib/hog-charts/core/scales.test.ts
+++ b/frontend/src/lib/hog-charts/core/scales.test.ts
@@ -6,6 +6,7 @@ import {
computeDivergingStackData,
computePercentStackData,
computeStackData,
+ createBarScales,
createScales,
createXScale,
createYScale,
@@ -701,4 +702,52 @@ describe('hog-charts scales', () => {
expect(resolve(b, 1)).toBeCloseTo(15 / 35, 5)
})
})
+
+ describe('createBarScales — horizontal fitToHeight', () => {
+ // plotHeight 100 / minBandSize 24 => 4 rows fit.
+ const shortDims = { ...dimensions, plotTop: 0, plotHeight: 100 }
+ const labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
+ const series = [makeSeries({ key: 's', data: labels.map((_, i) => 10 - i) })]
+
+ it('caps the band domain to the rows that fit at minBandSize, keeping the leading rows', () => {
+ const { band } = createBarScales(series, labels, shortDims, {
+ axisOrientation: 'horizontal',
+ fitToHeight: true,
+ minBandSize: 24,
+ })
+ expect(band.domain()).toEqual(['a', 'b', 'c', 'd'])
+ expect(band.bandwidth()).toBeGreaterThanOrEqual(20)
+ })
+
+ it('keeps every row when they all fit', () => {
+ const { band } = createBarScales(
+ series.map((s) => ({ ...s, data: [1, 2, 3] })),
+ ['a', 'b', 'c'],
+ shortDims,
+ {
+ axisOrientation: 'horizontal',
+ fitToHeight: true,
+ minBandSize: 24,
+ }
+ )
+ expect(band.domain()).toEqual(['a', 'b', 'c'])
+ })
+
+ it('does not cap when fitToHeight is off (grow-to-fit-all behavior)', () => {
+ const { band } = createBarScales(series, labels, shortDims, {
+ axisOrientation: 'horizontal',
+ minBandSize: 24,
+ })
+ expect(band.domain()).toEqual(labels)
+ })
+
+ it('ignores fitToHeight for vertical charts', () => {
+ const { band } = createBarScales(series, labels, shortDims, {
+ axisOrientation: 'vertical',
+ fitToHeight: true,
+ minBandSize: 24,
+ })
+ expect(band.domain()).toEqual(labels)
+ })
+ })
})
diff --git a/frontend/src/lib/hog-charts/core/scales.ts b/frontend/src/lib/hog-charts/core/scales.ts
index 84e246b56fb8..69c7778cc33e 100644
--- a/frontend/src/lib/hog-charts/core/scales.ts
+++ b/frontend/src/lib/hog-charts/core/scales.ts
@@ -387,6 +387,11 @@ export function createBarScales(
stackedSeries?: Series[]
/** Cap on the band-axis range in px — clusters bars at the start of the plot when set. */
maxBandRange?: number
+ /** Horizontal fit-to-height mode: drop the rows that can't fit at `minBandSize` so bands
+ * never crush below it and the plot fills the height it's given. Requires `minBandSize`. */
+ fitToHeight?: boolean
+ /** Minimum px per row — only consulted to compute the `fitToHeight` row cap. */
+ minBandSize?: number
/** Fixed `[min, max]` or `{ include }` extra values the value axis must cover. */
valueDomain?: ValueDomain
} = {}
@@ -399,6 +404,8 @@ export function createBarScales(
groupPadding = 0.1,
stackedSeries,
maxBandRange,
+ fitToHeight,
+ minBandSize,
valueDomain,
} = options
@@ -408,9 +415,20 @@ export function createBarScales(
const bandAxisStart = isHorizontal ? dimensions.plotTop : dimensions.plotLeft
const bandAxisExtent = isHorizontal ? dimensions.plotHeight : dimensions.plotWidth
const cappedExtent = maxBandRange != null ? Math.min(bandAxisExtent, maxBandRange) : bandAxisExtent
+
+ // Fit-to-height: only keep the rows that fit at `minBandSize`. Labels arrive value-sorted, so
+ // slicing keeps the leading rows. Bars/labels/grid all resolve through `band(label)`, so a
+ // dropped label resolves to `undefined` and is skipped everywhere — no extra plumbing needed.
+ let domainLabels = labels
+ if (isHorizontal && fitToHeight && minBandSize && minBandSize > 0) {
+ const maxBands = Math.max(1, Math.floor(cappedExtent / minBandSize))
+ if (labels.length > maxBands) {
+ domainLabels = labels.slice(0, maxBands)
+ }
+ }
const band = d3
.scaleBand<string>()
- .domain(labels)
+ .domain(domainLabels)
.range([bandAxisStart, bandAxisStart + cappedExtent])
.paddingInner(bandPadding)
.paddingOuter(bandPadding / 2)
diff --git a/frontend/src/lib/hog-charts/core/types.ts b/frontend/src/lib/hog-charts/core/types.ts
index 1cba07af931a..97be43aba06e 100644
--- a/frontend/src/lib/hog-charts/core/types.ts
+++ b/frontend/src/lib/hog-charts/core/types.ts
@@ -245,6 +245,11 @@ export interface BarsConfig {
* an unreadable strip, the chart expands its container height so each row has at least this
* much vertical space (label height + breathing room). Defaults to `24`. Pass `0` to opt out. */
minBandSize?: number
+ /** Horizontal bar charts only — fit the chart to the height it's given instead of expanding the
+ * container (the {@link minBandSize} default behavior). Rows that don't fit at `minBandSize` are
+ * dropped, keeping the leading (value-sorted) rows, so bands never crush below `minBandSize` and
+ * the container never grows or scrolls. Use inside fixed-height tiles such as dashboard cards. */
+ fitToHeight?: boolean
/** Value-axis domain control — omit for data-derived auto-scaling. See {@link ValueDomain}. */
valueDomain?: ValueDomain
/** Stacked layouts only — round both *outer* ends of the whole stack so it reads as one pill,
diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
index adc4be37d9e7..424a4c5fdb50 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/TrendsBarChart.tsx
@@ -77,7 +77,7 @@ const handleChartError = makeChartErrorHandler('trends-bar-chart')
export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChartProps): JSX.Element | null {
const theme = useMemo(() => buildTheme(), [])
- const { insightProps, insight } = useValues(insightLogic)
+ const { insightProps, insight, isInDashboardContext } = useValues(insightLogic)
const {
indexedResults,
@@ -237,6 +237,9 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
xTickFormatter,
xAxisLabel: trendsFilter?.xAxisLabel,
yAxisLabel: trendsFilter?.yAxisLabel,
+ // On a dashboard the tile is a fixed height: fit the rows that fit instead of growing
+ // the tile and scrolling. On the full insight page, keep the grow-to-fit-all behavior.
+ bars: { fitToHeight: isInDashboardContext },
}
}, [
yAxisScaleType,
@@ -245,6 +248,7 @@ export function TrendsBarChart({ context, inSharedMode = false }: TrendsBarChart
trendsFilter?.yAxisLabel,
displayLabels,
labels,
+ isInDashboardContext,
])
const canHandleClick = !!context?.onDataPointClick || !!hasPersonsModal