Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Add setting to display percentages instead of values on stacked bar charts (#79922)

Andersonb1e7ed37dd0a
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index 3582c285fcc..a907b4630ee 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -241,6 +241,7 @@ export type TableColumnOrderSetting = {
export type StackType = "stacked" | "normalized" | null;
export type StackValuesDisplay = "total" | "all" | "series";
+export type StackValueFormat = "value" | "percentage";
export const numericScale = ["linear", "pow", "log"] as const;
export type NumericScale = (typeof numericScale)[number];
@@ -314,6 +315,9 @@ export type VisualizationSettings = {
/** Show aggregate labels for stacked chart segments. */
"graph.show_stack_values"?: StackValuesDisplay;
+ /** Render stacked chart segment labels as raw values or as percentages of the stack. */
+ "graph.stack_value_format"?: StackValueFormat;
+
/** Limit the number of categories before grouping the rest into an "Other" bucket. */
"graph.max_categories_enabled"?: boolean;
diff --git a/frontend/src/metabase/visualizations/echarts/cartesian/option/series.ts b/frontend/src/metabase/visualizations/echarts/cartesian/option/series.ts
index a0dfdb3ce19..48547b74c65 100644
--- a/frontend/src/metabase/visualizations/echarts/cartesian/option/series.ts
+++ b/frontend/src/metabase/visualizations/echarts/cartesian/option/series.ts
@@ -9,6 +9,7 @@ import _ from "underscore";
import { getTextColorForBackground } from "metabase/ui/colors/palette";
import { isNotNull } from "metabase/utils/types";
+import { formatValue } from "metabase/value-formatting";
import {
INDEX_KEY,
NEGATIVE_STACK_TOTAL_DATA_KEY,
@@ -31,16 +32,23 @@ import type {
NumericAxisScaleTransforms,
NumericXAxisModel,
SeriesModel,
+ StackModel,
StackTotalDataKey,
TimeSeriesXAxisModel,
XAxisModel,
} from "metabase/visualizations/echarts/cartesian/model/types";
import type { EChartsSeriesOption } from "metabase/visualizations/echarts/cartesian/option/types";
+import { getPercent } from "metabase/visualizations/echarts/tooltip/utils";
import type {
ComputedVisualizationSettings,
RenderingContext,
} from "metabase/visualizations/types";
-import type { RowValue, SeriesSettings, XAxisScale } from "metabase-types/api";
+import type {
+ DatasetColumn,
+ RowValue,
+ SeriesSettings,
+ XAxisScale,
+} from "metabase-types/api";
import type { ChartLayout, TicksRotation } from "../layout/types";
import {
@@ -58,6 +66,7 @@ import { getPadding } from "./ticks";
import { getSeriesYAxisIndex } from "./utils";
const MIN_LABEL_SPACING_PX = 40;
+const STACK_PERCENTAGE_DECIMALS = 2;
const getBlurLabelStyle = (
settings: ComputedVisualizationSettings,
@@ -375,16 +384,88 @@ export const computeBarWidth = (
return barWidth;
};
+export const getStackValuePercentage = (
+ datum: Datum,
+ stackSeriesKeys: DataKey[],
+ value: number,
+) => {
+ const isNonNegative = (num: number) => num >= 0;
+ const stackTotal = stackSeriesKeys.reduce((total, dataKey) => {
+ const seriesValue = datum[dataKey];
+ const hasSameSign =
+ typeof seriesValue === "number" &&
+ isNonNegative(value) === isNonNegative(seriesValue);
+
+ return hasSameSign ? total + seriesValue : total;
+ }, 0);
+
+ return stackTotal === 0 ? undefined : getPercent(stackTotal, value);
+};
+
+export const formatStackValuePercentage = (
+ percentage: number,
+ column: DatasetColumn | undefined,
+ settings: ComputedVisualizationSettings,
+) => {
+ const displayedPercentage = Number(
+ (percentage * 100).toFixed(STACK_PERCENTAGE_DECIMALS),
+ );
+ const minimumFractionDigits = Number.isInteger(displayedPercentage)
+ ? 0
+ : STACK_PERCENTAGE_DECIMALS;
+ const columnSettings = column ? settings.column?.(column) : undefined;
+
+ return String(
+ formatValue(percentage, {
+ column,
+ number_separators: columnSettings?.number_separators,
+ number_style: "percent",
+ minimumFractionDigits,
+ maximumFractionDigits: STACK_PERCENTAGE_DECIMALS,
+ }),
+ );
+};
+
+export const formatStackTotalLabel = (
+ stackValue: number,
+ transformedStackValue: number,
+ column: DatasetColumn | undefined,
+ formatter: LabelFormatter,
+ settings: ComputedVisualizationSettings,
+) => {
+ const showPercentages =
+ settings["graph.show_stack_values"] === "all" &&
+ settings["graph.stack_value_format"] === "percentage";
+
+ if (!showPercentages) {
+ return formatter(transformedStackValue);
+ }
+
+ if (stackValue === 0) {
+ return "";
+ }
+
+ const percentage = getPercent(stackValue, stackValue);
+ return percentage === undefined
+ ? ""
+ : formatStackValuePercentage(percentage, column, settings);
+};
+
export const buildEChartsStackLabelOptions = (
seriesModel: SeriesModel,
formatter: LabelFormatter | undefined,
originalDataset: ChartDataset,
renderingContext: RenderingContext,
+ settings: ComputedVisualizationSettings,
+ stackModel: StackModel | undefined,
): SeriesLabelOption | undefined => {
if (!formatter) {
return;
}
+ const showPercentages =
+ settings["graph.stack_value_format"] === "percentage" && stackModel != null;
+
return {
silent: true,
position: "inside",
@@ -407,6 +488,23 @@ export const buildEChartsStackLabelOptions = (
if (typeof value !== "number") {
return "";
}
+
+ if (showPercentages) {
+ const percentage = getStackValuePercentage(
+ datum,
+ stackModel.seriesKeys,
+ value,
+ );
+ if (percentage === undefined) {
+ return "";
+ }
+ return formatStackValuePercentage(
+ percentage,
+ seriesModel.column,
+ settings,
+ );
+ }
+
return formatter(value);
},
};
@@ -483,6 +581,7 @@ const buildEChartsBarSeries = (
chartWidth: number,
labelFormatter: LabelFormatter | undefined,
renderingContext: RenderingContext,
+ stackModel: StackModel | undefined,
xAxisIndex?: number,
): BarSeriesOption | BarSeriesOption[] => {
const stack = stackName ?? `bar_${seriesModel.dataKey}`;
@@ -527,6 +626,8 @@ const buildEChartsBarSeries = (
labelFormatter,
originalDataset,
renderingContext,
+ settings,
+ stackModel,
)
: buildEChartsLabelOptions(
seriesModel,
@@ -738,6 +839,7 @@ function getStackedDataLabelFormatter(
yAxisScaleTransforms: NumericAxisScaleTransforms,
signKey: StackTotalDataKey,
stackDataKeys: DataKey[],
+ stackColumn: DatasetColumn | undefined,
stackName: string | undefined,
formatter: LabelFormatter,
chartDataDensity: ComboChartDataDensity,
@@ -767,7 +869,13 @@ function getStackedDataLabelFormatter(
return "";
}
- return formatter(yAxisScaleTransforms.fromEChartsAxisValue(stackValue));
+ return formatStackTotalLabel(
+ stackValue,
+ yAxisScaleTransforms.fromEChartsAxisValue(stackValue),
+ stackColumn,
+ formatter,
+ settings,
+ );
};
}
@@ -863,6 +971,7 @@ export const getStackTotalsSeries = (
.map((s) => s.id)
.filter(isNotNull) as string[];
const firstSeriesInStack = seriesOptions[0];
+ const stackColumn = chartModel.columnByDataKey[stackDataKeys[0]];
const labelFormatter = firstSeriesInStack.stack
? chartModel.stackedLabelsFormatters?.[
@@ -885,6 +994,7 @@ export const getStackTotalsSeries = (
yAxisScaleTransforms,
POSITIVE_STACK_TOTAL_DATA_KEY,
stackDataKeys,
+ stackColumn,
firstSeriesInStack.stack,
labelFormatter,
chartModel.dataDensity,
@@ -903,6 +1013,7 @@ export const getStackTotalsSeries = (
yAxisScaleTransforms,
NEGATIVE_STACK_TOTAL_DATA_KEY,
stackDataKeys,
+ stackColumn,
firstSeriesInStack.stack,
labelFormatter,
chartModel.dataDensity,
@@ -990,7 +1101,13 @@ export const buildEChartsSeries = (
renderingContext,
panelIndex,
);
- case "bar":
+ case "bar": {
+ const stackModel =
+ chartModel.stackModels == null
+ ? undefined
+ : chartModel.stackModels.find((stackModel) =>
+ stackModel.seriesKeys.includes(seriesModel.dataKey),
+ );
return buildEChartsBarSeries(
chartModel.transformedDataset,
chartModel.dataset,
@@ -1007,8 +1124,10 @@ export const buildEChartsSeries = (
chartWidth,
chartModel.seriesLabelsFormatters?.[seriesModel.dataKey],
renderingContext,
+ stackModel,
panelIndex,
);
+ }
}
})
.flat()
diff --git a/frontend/src/metabase/visualizations/echarts/cartesian/option/series.unit.spec.ts b/frontend/src/metabase/visualizations/echarts/cartesian/option/series.unit.spec.ts
new file mode 100644
index 00000000000..8ad77d9d189
--- /dev/null
+++ b/frontend/src/metabase/visualizations/echarts/cartesian/option/series.unit.spec.ts
@@ -0,0 +1,138 @@
+import { X_AXIS_DATA_KEY } from "metabase/visualizations/echarts/cartesian/constants/dataset";
+import type { Datum } from "metabase/visualizations/echarts/cartesian/model/types";
+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";
+import {
+ createMockColumn,
+ createMockVisualizationSettings,
+} from "metabase-types/api/mocks";
+
+import {
+ formatStackTotalLabel,
+ formatStackValuePercentage,
+ getStackValuePercentage,
+} from "./series";
+
+const column = createMockColumn({
+ name: "count",
+ display_name: "Count",
+ base_type: "type/Integer",
+});
+
+const createSettings = (
+ overrides: Partial<ComputedVisualizationSettings> = {},
+) =>
+ createMockVisualizationSettings({
+ column: () => ({ number_separators: ".," }),
+ ...overrides,
+ });
+
+describe("getStackValuePercentage", () => {
+ const datum: Datum = {
+ [X_AXIS_DATA_KEY]: "Mixed signs",
+ positiveA: 60,
+ positiveB: 40,
+ negativeA: -30,
+ negativeB: -10,
+ nullValue: null,
+ };
+ const seriesKeys = [
+ "positiveA",
+ "positiveB",
+ "negativeA",
+ "negativeB",
+ "nullValue",
+ ];
+
+ it.each([
+ ["positiveA", 60, 0.6],
+ ["positiveB", 40, 0.4],
+ ["negativeA", -30, -0.75],
+ ["negativeB", -10, -0.25],
+ ])(
+ "calculates %s against the total for its sign",
+ (_dataKey, value, expected) => {
+ expect(getStackValuePercentage(datum, seriesKeys, value)).toBe(expected);
+ },
+ );
+
+ it("returns undefined when the relevant sign has no non-zero total", () => {
+ expect(
+ getStackValuePercentage(
+ { [X_AXIS_DATA_KEY]: "Zero", first: 0, second: 0 },
+ ["first", "second"],
+ 0,
+ ),
+ ).toBeUndefined();
+ });
+});
+
+describe("formatStackValuePercentage", () => {
+ const settings = createSettings();
+
+ it.each([
+ [0.6, "60%"],
+ [1 / 3, "33.33%"],
+ [0.125, "12.50%"],
+ [-0.75, "-75%"],
+ [-1, "-100%"],
+ ])("formats %s as %s", (percentage, expected) => {
+ expect(formatStackValuePercentage(percentage, column, settings)).toBe(
+ expected,
+ );
+ });
+});
+
+describe("formatStackTotalLabel", () => {
+ const rawValueFormatter = (value: unknown) => `raw:${value}`;
+
+ it.each([
+ [100, "100%"],
+ [-40, "-100%"],
+ ])(
+ "formats a %s stack total as a signed percentage when showing both",
+ (stackValue, expected) => {
+ const settings = createSettings({
+ "graph.show_stack_values": "all",
+ "graph.stack_value_format": "percentage",
+ });
+
+ expect(
+ formatStackTotalLabel(
+ stackValue,
+ stackValue,
+ column,
+ rawValueFormatter,
+ settings,
+ ),
+ ).toBe(expected);
+ },
+ );
+
+ it("does not display a percentage for a zero total", () => {
+ const settings = createSettings({
+ "graph.show_stack_values": "all",
+ "graph.stack_value_format": "percentage",
+ });
+
+ expect(
+ formatStackTotalLabel(0, 0, column, rawValueFormatter, settings),
+ ).toBe("");
+ });
+
+ it.each([
+ ["all", "value"],
+ ["total", "percentage"],
+ ] as const)(
+ "keeps the raw total for show_stack_values=%s and stack_value_format=%s",
+ (showStackValues, stackValueFormat) => {
+ const settings = createSettings({
+ "graph.show_stack_values": showStackValues,
+ "graph.stack_value_format": stackValueFormat,
+ });
+
+ expect(
+ formatStackTotalLabel(100, 42, column, rawValueFormatter, settings),
+ ).toBe("raw:42");
+ },
+ );
+});
diff --git a/frontend/src/metabase/visualizations/lib/settings/graph.ts b/frontend/src/metabase/visualizations/lib/settings/graph.ts
index 9d979a4dc50..a834d5582f0 100644
--- a/frontend/src/metabase/visualizations/lib/settings/graph.ts
+++ b/frontend/src/metabase/visualizations/lib/settings/graph.ts
@@ -556,6 +556,62 @@ export const GRAPH_DISPLAY_VALUES_SETTINGS: VisualizationSettingsDefinitions = {
getDefault: (_series, settings) => getDefaultShowStackValues(settings),
readDependencies: ["graph.show_values", "stackable.stack_type"],
},
+ "graph.stack_value_format": {
+ getSection: () => t`Display`,
+ get title() {
+ return t`Stack value format`;
+ },
+ widget: "radio",
+ getHidden: (series, vizSettings) => {
+ const hasBars = getSeriesDisplays(series, vizSettings).some(
+ (display) => display === "bar",
+ );
+
+ if (!hasBars || vizSettings["graph.show_values"] !== true) {
+ return true;
+ }
+
+ const stackType = vizSettings["stackable.stack_type"];
+
+ // For normalized stacks ("Stack - 100%"), always show the setting
+ if (stackType === "normalized") {
+ return false;
+ }
+
+ // For regular stacked charts, only show when segment values are visible
+ if (stackType === "stacked") {
+ return !(
+ vizSettings["graph.show_stack_values"] === "series" ||
+ vizSettings["graph.show_stack_values"] === "all"
+ );
+ }
+
+ // Hide for non-stacked charts
+ return true;
+ },
+ getProps: () => ({
+ options: [
+ {
+ get name() {
+ return t`Values`;
+ },
+ value: "value",
+ },
+ {
+ get name() {
+ return t`Percentages`;
+ },
+ value: "percentage",
+ },
+ ],
+ }),
+ getDefault: () => "value",
+ readDependencies: [
+ "graph.show_values",
+ "stackable.stack_type",
+ "graph.show_stack_values",
+ ],
+ },
"graph.label_value_formatting": {
getSection: () => t`Display`,
get title() {
diff --git a/frontend/src/metabase/visualizations/lib/settings/graph.unit.spec.ts b/frontend/src/metabase/visualizations/lib/settings/graph.unit.spec.ts
index 4ff7dd45c05..59cc7d6015f 100644
--- a/frontend/src/metabase/visualizations/lib/settings/graph.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/lib/settings/graph.unit.spec.ts
@@ -563,6 +563,132 @@ describe("GRAPH_DISPLAY_VALUES_SETTINGS", () => {
expect(isHidden).toBe(true);
});
});
+
+ describe("graph.stack_value_format", () => {
+ const getHidden = checkNotNull(
+ GRAPH_DISPLAY_VALUES_SETTINGS["graph.stack_value_format"]?.getHidden,
+ );
+ const getDefault = checkNotNull(
+ GRAPH_DISPLAY_VALUES_SETTINGS["graph.stack_value_format"]?.getDefault,
+ );
+
+ it("should be hidden on non-stacked charts", () => {
+ const isHidden = getHidden(
+ [
+ createMockSingleSeries({ display: "bar" }),
+ createMockSingleSeries({ display: "bar" }),
+ ],
+ {
+ series: (series) => ({ display: series.card.display }),
+ "stackable.stack_type": null,
+ "graph.show_values": true,
+ "graph.show_stack_values": "series",
+ },
+ );
+
+ expect(isHidden).toBe(true);
+ });
+
+ it("should be hidden when show_values is false", () => {
+ const isHidden = getHidden(
+ [
+ createMockSingleSeries({ display: "bar" }),
+ createMockSingleSeries({ display: "bar" }),
+ ],
+ {
+ series: (series) => ({ display: series.card.display }),
+ "stackable.stack_type": "stacked",
+ "graph.show_values": false,
+ "graph.show_stack_values": "series",
+ },
+ );
+
+ expect(isHidden).toBe(true);
+ });
+
+ it("should be hidden when show_stack_values is 'total'", () => {
+ const isHidden = getHidden(
+ [
+ createMockSingleSeries({ display: "bar" }),
+ createMockSingleSeries({ display: "bar" }),
+ ],
+ {
+ series: (series) => ({ display: series.card.display }),
+ "stackable.stack_type": "stacked",
+ "graph.show_values": true,
+ "graph.show_stack_values": "total",
+ },
+ );
+
+ expect(isHidden).toBe(true);
+ });
+
+ it("should not be hidden when conditions are met with 'series'", () => {
+ const isHidden = getHidden(
+ [
+ createMockSingleSeries({ display: "bar" }),
+ createMockSingleSeries({ display: "bar" }),
+ ],
+ {
+ series: (series) => ({ display: series.card.display }),
+ "stackable.stack_type": "stacked",
+ "graph.show_values": true,
+ "graph.show_stack_values": "series",
+ },
+ );
+
+ expect(isHidden).toBe(false);
+ });
+
+ it("should not be hidden when show_stack_values is 'all'", () => {
+ const isHidden = getHidden(
+ [
+ createMockSingleSeries({ display: "bar" }),
+ createMockSingleSeries({ display: "bar" }),
+ ],
+ {
+ series: (series) => ({ display: series.card.display }),
+ "stackable.stack_type": "stacked",
+ "graph.show_values": true,
+ "graph.show_stack_values": "all",
+ },
+ );
+
+ expect(isHidden).toBe(false);
+ });
+
+ it("should not be hidden on normalized stacks regardless of show_stack_values", () => {
+ const isHidden = getHidden(
+ [
+ createMockSingleSeries({ display: "bar" }),
+ createMockSingleSeries({ display: "bar" }),
+ ],
+ {
+ series: (series) => ({ display: series.card.display }),
+ "stackable.stack_type": "normalized",
+ "graph.show_values": true,
+ "graph.show_stack_values": "total",
+ },
+ );
+
+ expect(isHidden).toBe(false);
+ });
+
+ it("should default to 'value'", () => {
+ expect(getDefault([], {})).toBe("value");
+ });
+
+ it("should offer Values and Percentages options", () => {
+ const getProps = checkNotNull(
+ GRAPH_DISPLAY_VALUES_SETTINGS["graph.stack_value_format"]?.getProps,
+ );
+
+ expect(getProps([], {}, jest.fn(), {}, jest.fn()).options).toEqual([
+ { name: "Values", value: "value" },
+ { name: "Percentages", value: "percentage" },
+ ]);
+ });
+ });
});
describe("graph.tooltip_columns", () => {
diff --git a/frontend/src/metabase/visualizations/types/visualization.ts b/frontend/src/metabase/visualizations/types/visualization.ts
index 32a23fd83b1..d781b8472dc 100644
--- a/frontend/src/metabase/visualizations/types/visualization.ts
+++ b/frontend/src/metabase/visualizations/types/visualization.ts
@@ -523,6 +523,10 @@ export type VisualizationSettingsDefinitions = {
"graph.show_trendline"?: SeriesSettingDefinition<Value, Props>;
"graph.show_values"?: SeriesSettingDefinition<Value, Props>;
"graph.split_panels"?: SeriesSettingDefinition<Value, Props>;
+ "graph.stack_value_format"?: SeriesSettingDefinition<
+ Value,
+ ChartSettingSegmentedControlProps
+ >;
"graph.tooltip_columns"?: SeriesSettingDefinition<Value, Props>;
"graph.tooltip_type"?: SeriesSettingDefinition<Value, Props>;
"graph.x_axis._is_histogram"?: SeriesSettingDefinition<Value, Props>;