The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Omit negative values from treemap instead of producing wrong percentages (#77601)
Oleh Kbb8b550a21f0
diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.tsindex bb4f6d3aea1..7e0f1924e00 100644--- a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.ts+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.ts@@ -1,6 +1,8 @@import { NULL_DISPLAY_VALUE } from "metabase/utils/constants";import { sumMetric } from "metabase/visualizations/lib/dataset";import { getColumnDescriptors } from "metabase/visualizations/lib/graph/columns";+import { getNumberOr } from "metabase/visualizations/lib/settings/row-values";+import { treemapNegativesWarning } from "metabase/visualizations/lib/warnings";import { getKeyFromDimensionValue } from "metabase/visualizations/shared/settings/pie";import type { ComputedVisualizationSettings } from "metabase/visualizations/types";import type {@@ -64,6 +66,7 @@ export function getTreemapData(treemapColumns: TreemapChartColumns,treemapRows?: TreemapRow[],settings?: Pick<ComputedVisualizationSettings, "column">,+ showWarning?: (warning: string) => void,): TreemapTree {const [{@@ -90,17 +93,39 @@ export function getTreemapData(.map((row) => row.key),);+ const isRowEnabled = (row: RowValue[]) =>+ !userDisabledRows.has(getKeyFromDimensionValue(row[grouping.index]));++ const enabledRows = rows.filter(isRowEnabled);+ const areAllNegative =+ enabledRows.length > 0 &&+ enabledRows.every((row) => getNumberOr(row[value.index], 0) < 0);+const rootByKey = new Map<RowValue, TreemapNode>();const leafMapByRoot = new Map<TreemapNode, Map<RowValue, TreemapNode>>();rows.forEach((row, rowIndex) => {const groupingValue = row[grouping.index];- const metricValue = row[value.index];+ let metricValue = row[value.index];- if (userDisabledRows.has(getKeyFromDimensionValue(groupingValue))) {+ if (!isRowEnabled(row)) {return;}+ // Filter negatives per-row (before summing) so a parent's value always+ // equals the sum of its surviving leaves — required for treemap area+ // containment. This differs from the pie chart, which drops whole negative+ // groups but still sums negative rows into the aggregate.+ const numericValue = getNumberOr(metricValue, null);+ if (numericValue !== null && numericValue < 0) {+ if (areAllNegative) {+ metricValue = Math.abs(numericValue);+ } else {+ showWarning?.(treemapNegativesWarning().text);+ return;+ }+ }+const { node: rootNode } = getOrCreateNode({map: rootByKey,rawName: groupingValue,diff --git a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.unit.spec.ts b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.unit.spec.tsindex edb20df578f..fd87181a066 100644--- a/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.unit.spec.ts+++ b/frontend/src/metabase/visualizations/echarts/graph/treemap/model/data.unit.spec.ts@@ -290,6 +290,84 @@ describe("treemap data model", () => {},]);});++ it("omits negative values and warns when values are mixed sign", () => {+ const showWarning = jest.fn();+ const result = getTreemapData(+ makeRawSeries2Level([+ ["A", "x", 30],+ ["A", "x", -50],+ ["B", "x", 10],+ ]),+ treemapColumnsWithSub,+ undefined,+ undefined,+ showWarning,+ );++ expect(result).toEqual([+ {+ rawName: "A",+ displayName: "A",+ value: 30,+ rowIndices: [0],+ children: [+ { rawName: "x", displayName: "x", value: 30, rowIndices: [0] },+ ],+ },+ {+ rawName: "B",+ displayName: "B",+ value: 10,+ rowIndices: [2],+ children: [+ { rawName: "x", displayName: "x", value: 10, rowIndices: [2] },+ ],+ },+ ]);+ expect(showWarning).toHaveBeenCalledWith(+ "Negative values in measure column have been omitted from treemap chart.",+ );+ });++ it("drops a group entirely when all of its rows are negative in mixed data", () => {+ const showWarning = jest.fn();+ const result = getTreemapData(+ makeRawSeries1Level([+ ["A", 30],+ ["B", -50],+ ]),+ treemapColumns,+ undefined,+ undefined,+ showWarning,+ );++ expect(result).toEqual([+ { rawName: "A", displayName: "A", value: 30, rowIndices: [0] },+ ]);+ expect(showWarning).toHaveBeenCalledTimes(1);+ });++ it("falls back to absolute values when every value is negative", () => {+ const showWarning = jest.fn();+ const result = getTreemapData(+ makeRawSeries1Level([+ ["A", -30],+ ["B", -50],+ ]),+ treemapColumns,+ undefined,+ undefined,+ showWarning,+ );++ expect(result).toEqual([+ { rawName: "A", displayName: "A", value: 30, rowIndices: [0] },+ { rawName: "B", displayName: "B", value: 50, rowIndices: [1] },+ ]);+ expect(showWarning).not.toHaveBeenCalled();+ });});describe("getNodesFromPath", () => {diff --git a/frontend/src/metabase/visualizations/lib/warnings.ts b/frontend/src/metabase/visualizations/lib/warnings.tsindex b57e164ccba..19ab694a69c 100644--- a/frontend/src/metabase/visualizations/lib/warnings.ts+++ b/frontend/src/metabase/visualizations/lib/warnings.ts@@ -9,6 +9,7 @@ const UNAGGREGATED_DATA_WARNING_PIE = "UNAGGREGATED_DATA_WARNING_PIE";const UNEXPECTED_QUERY_TIMEZONE = "UNEXPECTED_QUERY_TIMEZONE";const MULTIPLE_TIMEZONES = "MULTIPLE_TIMEZONES";const PIE_NEGATIVES = "PIE_NEGATIVES";+const TREEMAP_NEGATIVES = "TREEMAP_NEGATIVES";type VisualizationWarningKey =| typeof NULL_DIMENSION_WARNING@@ -17,7 +18,8 @@ type VisualizationWarningKey =| typeof UNAGGREGATED_DATA_WARNING_PIE| typeof UNEXPECTED_QUERY_TIMEZONE| typeof MULTIPLE_TIMEZONES- | typeof PIE_NEGATIVES;+ | typeof PIE_NEGATIVES+ | typeof TREEMAP_NEGATIVES;export type VisualizationWarning = {key: VisualizationWarningKey;@@ -90,3 +92,10 @@ export function pieNegativesWarning(): VisualizationWarning {text: t`Negative values in measure column have been omitted from pie chart.`,};}++export function treemapNegativesWarning(): VisualizationWarning {+ return {+ key: TREEMAP_NEGATIVES,+ text: t`Negative values in measure column have been omitted from treemap chart.`,+ };+}diff --git a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.tsx b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.tsxindex c5a32bad4af..1da5afe289f 100644--- a/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.tsx+++ b/frontend/src/metabase/visualizations/visualizations/TreemapChart/TreemapChart.tsx@@ -42,6 +42,7 @@ export const TreemapChart = ({settings,fontFamily,onVisualizationClick,+ onRender,clicked,isDashboard,isDocument,@@ -52,6 +53,11 @@ export const TreemapChart = ({[rawSeries],);+ const showWarning = useCallback(+ (warning: string) => onRender({ warnings: [warning] }),+ [onRender],+ );+const containerRef = useRef<HTMLDivElement>(null);const chartRef = useRef<EChartsType>();const overlayRef = useRef<TreemapHoverOverlay | null>(null);@@ -72,10 +78,11 @@ export const TreemapChart = ({treemapColumns,treemapRows,settings,+ showWarning,);const colors = getTreemapColors(tree, treemapRows);return { tree, colors, treemapColumns };- }, [rawSeriesWithRemappings, settings]);+ }, [rawSeriesWithRemappings, settings, showWarning]);const { viewRootId, viewRootIdRef, setViewRoot } = useTreemapNavigation(chartData?.tree ?? null,