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): render trends box plot with quill-charts (#64053)

Sam Pennington277c9f794bff
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index a0506e154efc..0811af581f0a 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -178,7 +178,6 @@ const config: Config = {
'^remark-gfm$': '<rootDir>/src/test/mocks/emptyMock.js',
'^mdast-util-find-and-replace$': '<rootDir>/src/test/mocks/emptyMock.js',
'^chart\\.js$': '<rootDir>/src/test/insight-testing/chartjs-mock',
- '@sgratzl/chartjs-chart-boxplot': '<rootDir>/src/test/mocks/emptyMock.js',
'chartjs-plugin-crosshair': '<rootDir>/src/test/mocks/emptyMock.js',
'chartjs-plugin-annotation': '<rootDir>/src/test/mocks/chartjsPluginMock.js',
'chartjs-plugin-datalabels': '<rootDir>/src/test/mocks/chartjsPluginMock.js',
diff --git a/frontend/package.json b/frontend/package.json
index eaa4504d7a06..06895d6ff67c 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -140,7 +140,6 @@
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-toggle-group": "^1.1.11",
"@react-hook/size": "^2.1.2",
- "@sgratzl/chartjs-chart-boxplot": "^4.4.5",
"@simplewebauthn/browser": "^13.2.2",
"@stripe/react-stripe-js": "^2.8.0",
"@stripe/stripe-js": "^4.5.0",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2367b1f0316c..3ffa0eb78724 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5577,13 +5577,13 @@ snapshots:
scenes-app-insights-sqllinechart--sql-line-chart-trend-line-quill--light:
hash: v1.k794b7964.00048bccb76c666facae706fc4884b75e8bf6caf39329fb2fb77d8ce8820829c.CkTMrfpT9rk-hAjJY_sB8dNew8PsEo_CGQSlg6u36NM
scenes-app-insights-trendsboxplot--trends-box-plot--dark:
- hash: v1.k794b7964.9421d408ac158259cf9c8120e5a4df7e79c87c38f48ff2fb096528ab4c21ccaa.kTH1yU4rwh9ATB6Xt9KnTZi2ZhBZM2uG_hsgwQ47kVY
+ hash: v1.k794b7964.25108b6d3d5af482598313f6b68fd028675b247c0d17e5779be0d3d4b411ea96.zuhAcP5NLyqADuY822ABYjVEbBR1NuF0JTIjmxgn9Y4
scenes-app-insights-trendsboxplot--trends-box-plot--light:
- hash: v1.k794b7964.46f6b6ec13e8eb66acce57e37b277ae26667d6f24f08b183a7301b9e5b71f63a._m3VcLunDQQ91j1xowLgs36l5pcio8ZBM_IdA3hEclU
+ hash: v1.k794b7964.2355058bafe94c8e9906b06b1a65c9f4137a319c8eb1f124fe0b8f33a722ed64.bTL1TD7U96ijFqIhFWYBE06pJCqXXZg8uzPmbD1BbHE
scenes-app-insights-trendsboxplot--trends-box-plot-edit--dark:
- hash: v1.k794b7964.a44e0ceccf278166f1813212b79e536cb88844f3d1d344c16de7b27a7e22f922.0K9H7VtJOtggpNtwlrIBHV2Tbe_V1VvkL_K44SIT6R8
+ hash: v1.k794b7964.5e62a26ad8dd2c907de5d8c6ace9749d3e0a4552425582db410a06637285fd2d.ACwD21kQdVzq4ieRF3b-_Je_TAVRUjkj-p9EmA8J0WU
scenes-app-insights-trendsboxplot--trends-box-plot-edit--light:
- hash: v1.k794b7964.7357d5bc4368db2240237131335e8b44a5a153211856a611267638fd4a389a4b.r3ZcjHo4heeqDVbloPPMqezcIa6OhFmVi5QnWLsQ2iw
+ hash: v1.k794b7964.0f04f4d2f31d4cd168f602fdf52c6c4dd671e13ebdcb3f2d55e474d5150bef89.6dyqUrim2JP9x4p2RvB43VD4zeGVHGi-hmPKPQe_Heg
scenes-app-insights-trendsmetric--trends-metric--dark:
hash: v1.k794b7964.78702e7b3a96182cce0f0093fd66d6a6b3ca7d9a61cda74804a033eb2a19d1e2.SnoS_KhAKCQGWymkhwtZ8ygxj2FzF-GN7Gm5HF36m5U
scenes-app-insights-trendsmetric--trends-metric--light:
diff --git a/frontend/src/lib/Chart.ts b/frontend/src/lib/Chart.ts
index e9b51667fafb..1e35a6277844 100644
--- a/frontend/src/lib/Chart.ts
+++ b/frontend/src/lib/Chart.ts
@@ -1,7 +1,6 @@
/* oxlint-disable no-restricted-imports */
import 'chartjs-adapter-dayjs-3'
-import { BoxAndWiskers, BoxPlotController } from '@sgratzl/chartjs-chart-boxplot'
import { ChartType, DefaultDataPoint, Chart as RawChart, Tooltip, registerables } from 'chart.js'
import CrosshairPlugin from 'chartjs-plugin-crosshair'
import ZoomPlugin from 'chartjs-plugin-zoom'
@@ -14,7 +13,6 @@ if (registerables) {
}
RawChart.register(CrosshairPlugin)
RawChart.register(ZoomPlugin)
-RawChart.register(BoxPlotController, BoxAndWiskers)
RawChart.defaults.animation = false
// Create positioner to put tooltip at cursor position
diff --git a/frontend/src/scenes/insights/views/BoxPlot/BoxPlotChart.tsx b/frontend/src/scenes/insights/views/BoxPlot/BoxPlotChart.tsx
index 468d5f3476dd..b2841e067b36 100644
--- a/frontend/src/scenes/insights/views/BoxPlot/BoxPlotChart.tsx
+++ b/frontend/src/scenes/insights/views/BoxPlot/BoxPlotChart.tsx
@@ -1,20 +1,22 @@
import { useValues } from 'kea'
-import { useCallback, useEffect, useRef } from 'react'
+import { useCallback, useMemo } from 'react'
+
+import { BoxPlot } from '@posthog/quill-charts'
+import type { BoxPlotClickData, BoxPlotConfig, BoxPlotSeries, BoxPlotTooltipContext } from '@posthog/quill-charts'
import 'scenes/insights/InsightTooltip/InsightTooltip.scss'
-import { Chart, ChartConfiguration, ChartEvent } from 'lib/Chart'
-import { getGraphColors, getSeriesColor } from 'lib/colors'
+import { buildTheme } from 'lib/charts/utils/theme'
+import { getSeriesColor } from 'lib/colors'
import { DateDisplay } from 'lib/components/DateDisplay'
import { SeriesLetter } from 'lib/components/SeriesGlyph'
-import { useChart } from 'lib/hooks/useChart'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { insightLogic } from 'scenes/insights/insightLogic'
import { InsightTooltip } from 'scenes/insights/InsightTooltip/InsightTooltip'
import { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'
-import { useInsightTooltip } from 'scenes/insights/useInsightTooltip'
import { teamLogic } from 'scenes/teamLogic'
import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { BoxPlotDatum, InsightActorsQuery, NodeKind } from '~/queries/schema/schema-general'
import { ChartParams } from '~/types'
@@ -55,67 +57,59 @@ function seriesDataToTooltip(seriesGroups: BoxPlotSeriesData[], dataIndex: numbe
return result
}
-function dayForIndex(seriesGroups: BoxPlotSeriesData[], dataIndex: number): string | null {
- const datum = seriesGroups[0]?.rawData[dataIndex]
- return datum?.day ?? null
-}
-
-function hasDataAtIndex(seriesGroups: BoxPlotSeriesData[], dataIndex: number): boolean {
- return !!seriesGroups[0]?.rawData[dataIndex]
-}
-
-function getNearestDataIndex(chart: Chart, event: ChartEvent | { x: number; y: number }): number | null {
- const xScale = chart.scales.x
- if (!xScale || event.x == null) {
- return null
- }
- const labels = xScale.ticks
- if (!labels || labels.length === 0) {
- return null
- }
-
- let closestIndex = 0
- let closestDistance = Infinity
- for (let i = 0; i < labels.length; i++) {
- const tickX = xScale.getPixelForTick(i)
- const distance = Math.abs(event.x - tickX)
- if (distance < closestDistance) {
- closestDistance = distance
- closestIndex = i
- }
- }
- return closestIndex
-}
-
export function BoxPlotChart({ showPersonsModal = true }: ChartParams): JSX.Element {
const { insightProps } = useValues(insightLogic)
const { boxplotData, seriesGroups, dateLabels, yAxisScaleType, querySource, interval, insightData, trendsFilter } =
useValues(boxPlotChartLogic(insightProps))
const { timezone, weekStartDay } = useValues(teamLogic)
+ const { isDarkModeOn } = useValues(themeLogic)
+
+ // isDarkModeOn invalidates the memo so buildTheme() re-reads CSS vars on dark-mode toggle.
+ const theme = useMemo(() => buildTheme(), [isDarkModeOn])
+
+ const series = useMemo<BoxPlotSeries[]>(
+ () =>
+ seriesGroups.map((group) => ({
+ key: String(group.seriesIndex),
+ label: group.seriesLabel,
+ // Explicit color keeps boxes in sync with BoxPlotLegend / BoxPlotResultsTable.
+ color: getSeriesColor(group.seriesIndex),
+ // Feed whisker bounds as min/max — quill draws whiskers at min/max, so this
+ // preserves the exclude-outliers (±1.5·IQR) behaviour computed in the logic.
+ data: group.rawData.map((raw, i) => ({
+ min: group.data[i].whiskerMin,
+ p25: raw.p25,
+ median: raw.median,
+ mean: raw.mean,
+ p75: raw.p75,
+ max: group.data[i].whiskerMax,
+ day: raw.day,
+ })),
+ })),
+ [seriesGroups]
+ )
- const colors = getGraphColors()
-
- const { getTooltip, hideTooltip, positionTooltip } = useInsightTooltip()
- const activeIndexRef = useRef<number | null>(null)
+ const config = useMemo<BoxPlotConfig>(
+ () => ({
+ yScaleType: yAxisScaleType === 'log10' ? 'log' : 'linear',
+ yTickFormatter: (value: number) => formatAggregationAxisValue(trendsFilter, value),
+ showGrid: true,
+ }),
+ [yAxisScaleType, trendsFilter]
+ )
- const showTooltipForIndex = useCallback(
- (chart: Chart, dataIndex: number, caretX: number, caretY: number) => {
- const day = dayForIndex(seriesGroups, dataIndex)
+ const renderTooltip = useCallback(
+ (ctx: BoxPlotTooltipContext): JSX.Element | null => {
+ const dataIndex = ctx.dataIndex
+ const day = seriesGroups[0]?.rawData[dataIndex]?.day
if (!seriesGroups.length || !day) {
- return
+ return null
}
- const [tooltipRoot, tooltipEl] = getTooltip()
- tooltipEl.classList.remove('above', 'below', 'no-transform', 'opacity-0', 'invisible')
- tooltipEl.classList.add('no-transform')
- tooltipEl.style.opacity = '1'
-
- const seriesData = seriesDataToTooltip(seriesGroups, dataIndex)
-
- tooltipRoot.render(
+ return (
<InsightTooltip
date={day}
timezone={timezone}
- seriesData={seriesData}
+ seriesData={seriesDataToTooltip(seriesGroups, dataIndex)}
interval={interval}
dateRange={insightData?.resolved_date_range}
hideColorCol={seriesGroups.length === 1}
@@ -137,25 +131,20 @@ export function BoxPlotChart({ showPersonsModal = true }: ChartParams): JSX.Elem
groupTypeLabel="people"
/>
)
-
- const bounds = chart.canvas.getBoundingClientRect()
- positionTooltip(tooltipEl, bounds, caretX, caretY)
},
- [seriesGroups, getTooltip, positionTooltip, timezone, interval, insightData, showPersonsModal, trendsFilter]
+ [seriesGroups, timezone, interval, insightData, showPersonsModal, trendsFilter]
)
- const handleClick = useCallback(
- (chart: Chart, event: ChartEvent) => {
- if (!showPersonsModal || !querySource || event.x == null) {
+ const handleBoxClick = useCallback(
+ (data: BoxPlotClickData): void => {
+ if (!showPersonsModal || !querySource) {
return
}
- const dataIndex = getNearestDataIndex(chart, event)
- if (dataIndex === null || !hasDataAtIndex(seriesGroups, dataIndex)) {
+ const day = seriesGroups[0]?.rawData[data.dataIndex]?.day
+ if (!day) {
return
}
- const day = dayForIndex(seriesGroups, dataIndex)!
-
const actorsQuery: InsightActorsQuery = {
kind: NodeKind.InsightActorsQuery,
source: querySource,
@@ -188,143 +177,21 @@ export function BoxPlotChart({ showPersonsModal = true }: ChartParams): JSX.Elem
[showPersonsModal, querySource, seriesGroups, interval, insightData, timezone, weekStartDay]
)
- const { canvasRef } = useChart({
- getConfig: () => {
- if (!boxplotData || boxplotData.length === 0 || seriesGroups.length === 0) {
- return null
- }
-
- const datasets = seriesGroups.map((group) => {
- const seriesColor = getSeriesColor(group.seriesIndex)
- return {
- label: group.seriesLabel,
- data: group.data,
- backgroundColor: `${seriesColor}40`,
- borderColor: seriesColor,
- borderWidth: 1.5,
- medianColor: seriesColor,
- meanBackgroundColor: `${seriesColor}80`,
- meanBorderColor: seriesColor,
- meanRadius: 3,
- outlierBackgroundColor: `${seriesColor}80`,
- outlierBorderColor: seriesColor,
- minStats: 'whiskerMin' as const,
- maxStats: 'whiskerMax' as const,
- }
- })
-
- return {
- type: 'boxplot' as const,
- data: {
- labels: dateLabels,
- datasets,
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- animation: { duration: 0 },
- onClick(event: ChartEvent, _elements: unknown[], chart: Chart) {
- handleClick(chart, event)
- },
- onHover(event: ChartEvent, _elements: unknown[], chart: Chart) {
- if (event.x == null) {
- if (activeIndexRef.current !== null) {
- activeIndexRef.current = null
- hideTooltip()
- }
- return
- }
- const dataIndex = getNearestDataIndex(chart, event)
- if (dataIndex === null) {
- if (activeIndexRef.current !== null) {
- activeIndexRef.current = null
- hideTooltip()
- }
- return
- }
- if (activeIndexRef.current !== dataIndex) {
- activeIndexRef.current = dataIndex
- const tickX = chart.scales.x?.getPixelForTick(dataIndex) ?? event.x
- showTooltipForIndex(chart, dataIndex, tickX, 0)
- }
-
- chart.canvas.style.cursor = showPersonsModal ? 'pointer' : 'default'
- },
- plugins: {
- legend: { display: false },
- tooltip: { enabled: false },
- crosshair: {
- snap: { enabled: true },
- sync: { enabled: false },
- zoom: { enabled: false },
- line: {
- color: colors.crosshair ?? undefined,
- width: 1,
- },
- },
- zoom: { zoom: { drag: { enabled: false } } },
- },
- scales: {
- x: {
- ticks: {
- color: colors.axisLabel as string,
- font: { size: 12 },
- },
- grid: { display: false },
- },
- y: {
- type: yAxisScaleType === 'log10' ? 'logarithmic' : 'linear',
- ticks: {
- color: colors.axisLabel as string,
- font: { size: 12 },
- callback: (value) => {
- return formatAggregationAxisValue(trendsFilter, value)
- },
- },
- grid: {
- color: colors.axisLine as string,
- borderColor: colors.axisLine as string,
- },
- },
- },
- },
- plugins: [],
- } as ChartConfiguration<'boxplot'>
- },
- deps: [
- boxplotData,
- seriesGroups,
- dateLabels,
- colors,
- showTooltipForIndex,
- hideTooltip,
- yAxisScaleType,
- handleClick,
- showPersonsModal,
- trendsFilter,
- ],
- })
-
- useEffect(() => {
- const canvas = canvasRef.current
- if (!canvas) {
- return
- }
- const onMouseLeave = (): void => {
- activeIndexRef.current = null
- hideTooltip()
- }
- canvas.addEventListener('mouseleave', onMouseLeave)
- return () => canvas.removeEventListener('mouseleave', onMouseLeave)
- }, [hideTooltip, canvasRef.current])
-
if (!boxplotData || boxplotData.length === 0) {
return <div className="flex items-center justify-center h-full text-muted">No data for this time range</div>
}
return (
- <div className="w-full grow relative overflow-hidden" data-attr="box-plot-graph">
- <canvas ref={canvasRef} />
+ <div className="w-full grow relative overflow-hidden flex flex-col">
+ <BoxPlot
+ series={series}
+ labels={dateLabels}
+ theme={theme}
+ config={config}
+ tooltip={renderTooltip}
+ onBoxClick={handleBoxClick}
+ dataAttr="box-plot-graph"
+ />
</div>
)
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 76d316529167..46ea99f0646d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -819,9 +819,6 @@ importers:
'@react-hook/size':
specifier: ^2.1.2
version: 2.1.2([email protected])
- '@sgratzl/chartjs-chart-boxplot':
- specifier: ^4.4.5
- version: 4.4.5([email protected])
'@simplewebauthn/browser':
specifier: ^13.2.2
version: 13.2.2
@@ -10403,14 +10400,6 @@ packages:
resolution: {integrity: sha512-YlEBwybUcOQ/KjMHDmof1vwweVnBtBxYlQp7DE3fOdtW4pqqdHWTnTntQs4VgYfxzjJYgtkd9LHlGtg8qy+JVQ==}
engines: {node: '>=14.18'}
- '@sgratzl/[email protected]':
- resolution: {integrity: sha512-XHQTNTk0OtDEZyT7v+BKNKt4OEXYhn4GtfI+iQ1eFiFsx8Aq/csz+mOJYbfpkiP8Popd/8Nky8vLh1zzkYn0gw==}
-
- '@sgratzl/[email protected]':
- resolution: {integrity: sha512-hvHcUIPIyzNPRmvPNIbA/R68zZKv7XHUcNrYJZTB8QsVE0KKuuGuEK98yCeCy32vZXQBl/PrHGOYMXeuqZrU0w==}
- peerDependencies:
- chart.js: ^4.1.1
-
'@shikijs/[email protected]':
resolution: {integrity: sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g==}
@@ -30654,13 +30643,6 @@ snapshots:
'@sentry/[email protected]': {}
- '@sgratzl/[email protected]': {}
-
- dependencies:
- '@sgratzl/boxplots': 2.0.0
- chart.js: 4.5.1
-
'@shikijs/[email protected]':
dependencies:
'@shikijs/types': 3.23.0
diff --git a/posthog/hogql_queries/insights/trends/boxplot_trends_query_runner.py b/posthog/hogql_queries/insights/trends/boxplot_trends_query_runner.py
index 547905034a4b..62fc354b7949 100644
--- a/posthog/hogql_queries/insights/trends/boxplot_trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/boxplot_trends_query_runner.py
@@ -10,6 +10,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.query import execute_hogql_query
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.hogql_queries.insights.trends.aggregation_operations import AggregationOperations
from posthog.hogql_queries.insights.trends.trends_query_builder import TrendsQueryBuilder
from posthog.hogql_queries.insights.trends.trends_query_runner import TrendsQueryRunner
@@ -101,15 +102,18 @@ class BoxPlotTrendsQueryRunner(TrendsQueryRunner):
debug_errors: list[str] = []
for series_index, series_label, boxplot_query in series_queries:
- response = execute_hogql_query(
- query_type="BoxPlotTrendsQuery",
- query=boxplot_query,
- team=self.team,
- user=self.user,
- timings=self.timings,
- modifiers=self.modifiers,
- limit_context=self.limit_context,
- )
+ # `BoxPlotTrendsQuery` isn't a NodeKind, so the fallback query tagger can't attribute
+ # it — tag it explicitly so the queries are attributed (and don't trip the untagged-query guard).
+ with tags_context(product=Product.PRODUCT_ANALYTICS, feature=Feature.QUERY):
+ response = execute_hogql_query(
+ query_type="BoxPlotTrendsQuery",
+ query=boxplot_query,
+ team=self.team,
+ user=self.user,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ )
if response.timings is not None:
all_timings.extend(response.timings)