Skip to content

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

feat(visualizations): give each y-axis its own label (#82881)

Aleksandr Lesnenkod8488ef969f6
diff --git a/e2e/test/scenarios/visualizations-charts/line_chart.cy.spec.js b/e2e/test/scenarios/visualizations-charts/line_chart.cy.spec.js
index 93a09d99ad0..f73e481ddee 100644
--- a/e2e/test/scenarios/visualizations-charts/line_chart.cy.spec.js
+++ b/e2e/test/scenarios/visualizations-charts/line_chart.cy.spec.js
@@ -516,6 +516,70 @@ describe("scenarios > visualizations > line chart", () => {
cy.get("g.axis.yr").should("not.exist");
});
+
+ it("should label each side of a split y-axis separately", () => {
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [
+ ["sum", ["field", ORDERS.TOTAL, null]],
+ ["min", ["field", ORDERS.TOTAL, null]],
+ ],
+ breakout: [
+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
+ ],
+ },
+ database: SAMPLE_DB_ID,
+ },
+ display: "line",
+ });
+
+ H.openVizSettingsSidebar();
+ H.vizSettingsSidebar().findByText("Axes").click();
+
+ cy.log("an unset right label inherits the left one");
+ H.vizSettingsSidebar()
+ .findByLabelText("Left axis label")
+ .clear()
+ .type("Revenue")
+ .blur();
+ H.vizSettingsSidebar()
+ .findByLabelText("Right axis label")
+ .should("have.value", "Revenue");
+ H.echartsContainer().findAllByText("Revenue").should("have.length", 2);
+
+ cy.log("the right label applies to the right axis only");
+ H.vizSettingsSidebar()
+ .findByLabelText("Right axis label")
+ .clear()
+ .type("Smallest order")
+ .blur();
+ H.echartsContainer()
+ .findByText("Revenue")
+ .then((leftLabel) => {
+ const { x: xLeft } = H.getXYTransform(leftLabel);
+ H.echartsContainer()
+ .findByText("Smallest order")
+ .then((rightLabel) => {
+ const { x: xRight } = H.getXYTransform(rightLabel);
+ expect(xRight).to.be.greaterThan(xLeft);
+ });
+ });
+
+ cy.log("a chart with one y-axis offers one label");
+ H.vizSettingsSidebar().findByText("Split y-axis when necessary").click();
+ H.echartsContainer().findByText("Revenue").should("be.visible");
+ H.echartsContainer().findByText("Smallest order").should("not.exist");
+ H.vizSettingsSidebar().findByDisplayValue("Revenue").should("be.visible");
+ H.vizSettingsSidebar()
+ .findByLabelText("Right axis label")
+ .should("not.exist");
+ H.vizSettingsSidebar()
+ .findByLabelText("Left axis label")
+ .should("not.exist");
+ });
});
describe("color series", () => {
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index 1519fc35867..12b0629f8bf 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -362,9 +362,12 @@ export type VisualizationSettings = {
/** Let Metabase choose the y-axis bounds automatically. */
"graph.y_axis.auto_range"?: boolean;
- /** Override the y-axis label. */
+ /** Override the y-axis label. On a split chart this labels the left axis. */
"graph.y_axis.title_text"?: string;
+ /** Override the right y-axis label on a split chart. Falls back to `graph.y_axis.title_text`. */
+ "graph.y_axis.right.title_text"?: string;
+
/** Y-axis numeric scale, such as linear, pow, or log. */
"graph.y_axis.scale"?: YAxisScale;
diff --git a/frontend/src/metabase/embedding-sdk/types/question.ts b/frontend/src/metabase/embedding-sdk/types/question.ts
index 0d638555c0e..f8efbbe9ccb 100644
--- a/frontend/src/metabase/embedding-sdk/types/question.ts
+++ b/frontend/src/metabase/embedding-sdk/types/question.ts
@@ -44,6 +44,7 @@ export type CartesianVisualizationSettings = Pick<
| "graph.x_axis.scale"
| "graph.x_axis.axis_enabled"
| "graph.y_axis.title_text"
+ | "graph.y_axis.right.title_text"
| "graph.y_axis.scale"
| "graph.y_axis.auto_range"
| "graph.y_axis.min"
diff --git a/frontend/src/metabase/visualizations/tests/settings-framework.unit.spec.ts b/frontend/src/metabase/visualizations/tests/settings-framework.unit.spec.ts
index 4096e87e0ca..d5f42240c44 100644
--- a/frontend/src/metabase/visualizations/tests/settings-framework.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/tests/settings-framework.unit.spec.ts
@@ -142,6 +142,14 @@ describe("settings framework", () => {
expect(getSection.mock.calls).toEqual([[mockObject, {}, {}]]);
});
+ it("should resolve title via `getTitle`", () => {
+ const getTitle = jest.fn().mockReturnValue("Bar");
+ const defs = { foo: { title: "Foo", widget: "input", getTitle } };
+ const widgets = getSettingsWidgets(defs, {}, {}, mockObject, () => {});
+ expect(widgets[0].title).toEqual("Bar");
+ expect(getTitle.mock.calls).toEqual([[mockObject, {}, {}]]);
+ });
+
it("should compute props when `getProps` is provided", () => {
const getProps = jest.fn().mockReturnValue({ hello: "world" });
const defs = { foo: { widget: "input", getProps } };
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-models-and-option.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-models-and-option.ts
index a3b0f87d61b..2eee798cd5f 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-models-and-option.ts
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/use-models-and-option.ts
@@ -70,6 +70,9 @@ export function useModelsAndOption(
settings["graph.y_axis.title_text"] = tc(
settings["graph.y_axis.title_text"],
);
+ settings["graph.y_axis.right.title_text"] = tc(
+ settings["graph.y_axis.right.title_text"],
+ );
getModel = getCartesianChartModel;
if (card.display === "waterfall") {
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/y-axis-label-settings.unit.spec.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/y-axis-label-settings.unit.spec.ts
new file mode 100644
index 00000000000..254f0c869d3
--- /dev/null
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/y-axis-label-settings.unit.spec.ts
@@ -0,0 +1,161 @@
+import { registerVisualizations } from "metabase/visualizations/register";
+import {
+ getSettingsWidgetsForSeries,
+ getVisualizationTransformed,
+} from "metabase/viz-core";
+import type { RowValue, VisualizationSettings } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockColumn,
+ createMockDatasetData,
+ createMockSingleSeries,
+} from "metabase-types/api/mocks";
+
+registerVisualizations();
+
+const MONTH = createMockColumn({
+ name: "month",
+ display_name: "Month",
+ base_type: "type/Text",
+ semantic_type: null,
+});
+const CATEGORY = createMockColumn({
+ name: "category",
+ display_name: "Category",
+ base_type: "type/Text",
+ semantic_type: "type/Category",
+});
+const REVENUE = createMockColumn({
+ name: "revenue",
+ display_name: "Revenue",
+ base_type: "type/Number",
+ semantic_type: null,
+});
+const ORDERS = createMockColumn({
+ name: "orders",
+ display_name: "Orders",
+ base_type: "type/Number",
+ semantic_type: null,
+});
+const QUANTITY = createMockColumn({
+ name: "quantity",
+ display_name: "Quantity",
+ base_type: "type/Number",
+ semantic_type: null,
+});
+
+const getLabelWidgets = (
+ cols: ReturnType<typeof createMockColumn>[],
+ rows: RowValue[][],
+ settings: VisualizationSettings,
+) => {
+ const rawSeries = [
+ createMockSingleSeries(
+ createMockCard({ display: "line", visualization_settings: settings }),
+ { data: createMockDatasetData({ cols, rows }) },
+ ),
+ ];
+ // The sidebar is handed the transformed series, as it is in the app.
+ const { series } = getVisualizationTransformed(rawSeries);
+ const widgets = getSettingsWidgetsForSeries(series, jest.fn());
+ const findWidget = (id: string) => widgets.find((widget) => widget.id === id);
+
+ return {
+ left: findWidget("graph.y_axis.title_text"),
+ right: findWidget("graph.y_axis.right.title_text"),
+ };
+};
+
+describe("y-axis label settings", () => {
+ it("should offer one label field when the chart has one axis", () => {
+ const { left, right } = getLabelWidgets(
+ [MONTH, CATEGORY, REVENUE],
+ [
+ ["Jan", "A", 1],
+ ["Jan", "B", 1000],
+ ["Feb", "A", 2],
+ ["Feb", "B", 900],
+ ],
+ {
+ "graph.dimensions": ["month", "category"],
+ "graph.metrics": ["revenue"],
+ },
+ );
+
+ expect(left).toMatchObject({ title: "Label", hidden: false });
+ expect(right?.hidden).toBe(true);
+ });
+
+ it("should offer a label per axis when the chart splits", () => {
+ const { left, right } = getLabelWidgets(
+ [MONTH, REVENUE, ORDERS],
+ [
+ ["Jan", 1, 900],
+ ["Feb", 2, 1000],
+ ],
+ {
+ "graph.dimensions": ["month"],
+ "graph.metrics": ["revenue", "orders"],
+ },
+ );
+
+ expect(left).toMatchObject({
+ title: "Left axis label",
+ hidden: false,
+ value: null,
+ });
+ expect(right).toMatchObject({
+ title: "Right axis label",
+ group: "Y-axis",
+ hidden: false,
+ });
+ });
+
+ describe("values on a split chart", () => {
+ const THREE_METRICS = {
+ "graph.dimensions": ["month"],
+ "graph.metrics": ["revenue", "orders", "quantity"],
+ };
+
+ it("should name the axis that plots one series when the other mixes two", () => {
+ const { left, right } = getLabelWidgets(
+ [MONTH, REVENUE, ORDERS, QUANTITY],
+ [
+ ["Jan", 900, 1, 800],
+ ["Feb", 1000, 2, 950],
+ ],
+ THREE_METRICS,
+ );
+
+ expect(left?.props.value).toBeUndefined();
+ expect(right?.props.value).toBe("Orders");
+ });
+
+ it("should name the left axis when the right one mixes two series", () => {
+ const { left, right } = getLabelWidgets(
+ [MONTH, REVENUE, ORDERS, QUANTITY],
+ [
+ ["Jan", 900, 1, 3],
+ ["Feb", 1000, 2, 4],
+ ],
+ THREE_METRICS,
+ );
+
+ expect(left?.props.value).toBe("Revenue");
+ expect(right?.props.value).toBeUndefined();
+ });
+
+ it("should show a typed left label on the right axis until it gets its own", () => {
+ const { right } = getLabelWidgets(
+ [MONTH, REVENUE, ORDERS, QUANTITY],
+ [
+ ["Jan", 900, 1, 800],
+ ["Feb", 1000, 2, 950],
+ ],
+ { ...THREE_METRICS, "graph.y_axis.title_text": "Money" },
+ );
+
+ expect(right?.props.value).toBe("Money");
+ });
+ });
+});
diff --git a/frontend/src/metabase/viz-core/echarts/boxplot/model/index.ts b/frontend/src/metabase/viz-core/echarts/boxplot/model/index.ts
index 0468d0f4a53..b967fc9c7c6 100644
--- a/frontend/src/metabase/viz-core/echarts/boxplot/model/index.ts
+++ b/frontend/src/metabase/viz-core/echarts/boxplot/model/index.ts
@@ -308,6 +308,7 @@ const createBoxPlotYAxisModel = (
columnByDataKey: Record<string, DatasetColumn>,
seriesExtents: SeriesExtents,
yAxisScaleTransforms: ReturnType<typeof getAxisTransforms>,
+ isSplitRightAxis = false,
): YAxisModel | null => {
if (dataKeys.length === 0) {
return null;
@@ -319,6 +320,7 @@ const createBoxPlotYAxisModel = (
dataset,
settings,
columnByDataKey,
+ { isSplitRightAxis },
);
if (yAxisModel) {
@@ -382,6 +384,7 @@ const getBoxPlotYAxesModels = (
columnByDataKey,
seriesExtents,
yAxisScaleTransforms,
+ leftAxisSeriesKeys.size > 0,
),
leftAxisSeriesKeys,
rightAxisSeriesKeys,
diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.ts
index c5776522e3e..34d60e81568 100644
--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.ts
+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.ts
@@ -68,10 +68,10 @@ const getMetricColumnsCount = (seriesModels: SeriesModel[]) => {
.length;
};
-export function shouldAutoSplitYAxis(
+// The checks of `shouldAutoSplitYAxis` that don't need series extents.
+function canAutoSplitYAxis(
settings: ComputedVisualizationSettings,
seriesModels: SeriesModel[],
- seriesExtents: SeriesExtents,
) {
if (!settings["graph.y_axis.auto_split"] || settings["graph.split_panels"]) {
return false;
@@ -80,10 +80,18 @@ export function shouldAutoSplitYAxis(
const isSingleCardWithSingleMetricColumn =
uniqueCards(seriesModels) <= 1 && getMetricColumnsCount(seriesModels) <= 1;
- if (
- isSingleCardWithSingleMetricColumn ||
- settings["stackable.stack_type"] != null
- ) {
+ return (
+ !isSingleCardWithSingleMetricColumn &&
+ settings["stackable.stack_type"] == null
+ );
+}
+
+export function shouldAutoSplitYAxis(
+ settings: ComputedVisualizationSettings,
+ seriesModels: SeriesModel[],
+ seriesExtents: SeriesExtents,
+) {
+ if (!canAutoSplitYAxis(settings, seriesModels)) {
return false;
}
@@ -228,10 +236,10 @@ export function computeSplit(
return best;
}
-const getYAxisSplit = (
+export const getYAxisSplit = (
seriesModels: SeriesModel[],
stackModels: StackModel[],
- seriesExtents: SeriesExtents,
+ dataset: ChartDataset,
settings: ComputedVisualizationSettings,
isAutoSplitSupported: boolean,
) => {
@@ -294,12 +302,20 @@ const getYAxisSplit = (
}
}
- if (
- !isAutoSplitSupported ||
- !shouldAutoSplitYAxis(settings, seriesModels, seriesExtents)
- ) {
- // assign all auto to the left
- return [new Set([...left, ...auto]), new Set(right)];
+ const allAutoLeft = [new Set([...left, ...auto]), new Set(right)];
+
+ // Extents take a pass over the rows, so skip them when no auto split can happen.
+ if (!isAutoSplitSupported || !canAutoSplitYAxis(settings, seriesModels)) {
+ return allAutoLeft;
+ }
+
+ const seriesExtents = getDatasetExtents(
+ seriesModels.map((seriesModel) => seriesModel.dataKey),
+ dataset,
+ );
+
+ if (!shouldAutoSplitYAxis(settings, seriesModels, seriesExtents)) {
+ return allAutoLeft;
}
// computes a split with all axis unassigned, then moves
@@ -418,15 +434,20 @@ export const getYAxisFormatter = (
};
};
-const getYAxisLabel = (
+export const getYAxisLabel = (
seriesNames: string[],
settings: ComputedVisualizationSettings,
+ isSplitRightAxis: boolean,
) => {
if (settings["graph.y_axis.labels_enabled"] === false) {
return undefined;
}
- const specifiedAxisName = settings["graph.y_axis.title_text"];
+ // An unset right label falls back to the left one; a blank one hides it.
+ const specifiedAxisName = isSplitRightAxis
+ ? (settings["graph.y_axis.right.title_text"] ??
+ settings["graph.y_axis.title_text"])
+ : settings["graph.y_axis.title_text"];
if (specifiedAxisName != null) {
return specifiedAxisName;
@@ -501,6 +522,7 @@ interface YAxisModelOptions {
formattingOptions?: ColumnSettings;
gridSize?: VisualizationGridSize;
showLabel?: boolean;
+ isSplitRightAxis?: boolean;
}
export function getYAxisModel(
@@ -517,6 +539,7 @@ export function getYAxisModel(
formattingOptions,
gridSize,
showLabel = true,
+ isSplitRightAxis = false,
} = options;
if (seriesKeys.length === 0) {
@@ -530,7 +553,9 @@ export function getYAxisModel(
stackType,
);
const column = columnByDataKey[seriesKeys[0]];
- const label = showLabel ? getYAxisLabel(seriesNames, settings) : undefined;
+ const label = showLabel
+ ? getYAxisLabel(seriesNames, settings, isSplitRightAxis)
+ : undefined;
const formatter = getYAxisFormatter(
column,
settings,
@@ -574,13 +599,10 @@ export function getYAxesModels(
isCompactFormatting: boolean,
gridSize?: VisualizationGridSize,
) {
- const seriesDataKeys = seriesModels.map((seriesModel) => seriesModel.dataKey);
- const extents = getDatasetExtents(seriesDataKeys, dataset);
-
const [leftAxisSeriesKeysSet, rightAxisSeriesKeysSet] = getYAxisSplit(
seriesModels,
stackModels,
- extents,
+ dataset,
settings,
isAutoSplitSupported,
);
@@ -636,6 +658,9 @@ export function getYAxesModels(
: (settings["stackable.stack_type"] ?? null),
formattingOptions: { compact: isCompactFormatting },
gridSize,
+ // A right axis alone uses the left label. Legend visibility must not
+ // change which label it uses.
+ isSplitRightAxis: leftAxisSeriesKeysSet.size > 0,
},
);
diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.unit.spec.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.unit.spec.ts
index 76772a8c91e..d6998a7d693 100644
--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.unit.spec.ts
+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/axis.unit.spec.ts
@@ -1,21 +1,33 @@
+import { createMockSeriesModel } from "__support__/echarts";
import { dayjs } from "metabase/dayjs";
-import type { RowValue } from "metabase-types/api";
+import { checkNotNull } from "metabase/utils/types";
+import type {
+ DatasetColumn,
+ RowValue,
+ SeriesSettings,
+} from "metabase-types/api";
import {
+ createMockColumn,
createMockDatetimeColumn,
createMockSingleSeries,
createMockVisualizationSettings,
} from "metabase-types/api/mocks";
+import type { ComputedVisualizationSettings } from "../../../types";
import { X_AXIS_DATA_KEY } from "../constants/dataset";
import {
computeSplit,
getXAxisDateRangeFromSortedXAxisValues,
getXAxisModel,
+ getYAxesModels,
} from "./axis";
import { isTimeSeriesAxis } from "./guards";
import type {
+ ChartDataset,
+ DataKey,
DimensionModel,
+ LegacySeriesSettingsObjectKey,
SeriesExtents,
TimeSeriesXAxisModel,
} from "./types";
@@ -182,3 +194,127 @@ describe("getXAxisDateRangeFromSortedXAxisValues", () => {
]);
});
});
+
+describe("getYAxesModels", () => {
+ const LEFT_SERIES_KEY = "revenue";
+ const RIGHT_SERIES_KEY = "orders";
+
+ const seriesModels = [
+ createMockSeriesModel({ dataKey: LEFT_SERIES_KEY }),
+ createMockSeriesModel({ dataKey: RIGHT_SERIES_KEY }),
+ ];
+
+ const dataset: ChartDataset = [
+ { [X_AXIS_DATA_KEY]: "Jan", [LEFT_SERIES_KEY]: 1, [RIGHT_SERIES_KEY]: 900 },
+ {
+ [X_AXIS_DATA_KEY]: "Feb",
+ [LEFT_SERIES_KEY]: 2,
+ [RIGHT_SERIES_KEY]: 1000,
+ },
+ ];
+
+ const columnByDataKey: Record<DataKey, DatasetColumn> = {
+ [LEFT_SERIES_KEY]: createMockColumn({ name: LEFT_SERIES_KEY }),
+ [RIGHT_SERIES_KEY]: createMockColumn({ name: RIGHT_SERIES_KEY }),
+ };
+
+ const assignSeriesToAxis = ({
+ card,
+ }: LegacySeriesSettingsObjectKey): SeriesSettings =>
+ card._seriesKey === RIGHT_SERIES_KEY ? { axis: "right" } : { axis: "left" };
+
+ const getSplitAxesModels = (settings: ComputedVisualizationSettings) =>
+ getYAxesModels(
+ seriesModels,
+ dataset,
+ dataset,
+ { series: assignSeriesToAxis, ...settings },
+ columnByDataKey,
+ true,
+ [],
+ false,
+ );
+
+ it("should label both axes with the legacy 'graph.y_axis.title_text' when no right-axis label is stored", () => {
+ const { leftAxisModel, rightAxisModel } = getSplitAxesModels({
+ "graph.y_axis.title_text": "Legacy label",
+ });
+
+ expect(checkNotNull(leftAxisModel).label).toBe("Legacy label");
+ expect(checkNotNull(rightAxisModel).label).toBe("Legacy label");
+ });
+
+ it("should hide the right label when it is cleared to blank", () => {
+ const { leftAxisModel, rightAxisModel } = getSplitAxesModels({
+ "graph.y_axis.title_text": "Orders placed",
+ "graph.y_axis.right.title_text": "",
+ });
+
+ expect(checkNotNull(leftAxisModel).label).toBe("Orders placed");
+ expect(checkNotNull(rightAxisModel).label).toBe("");
+ });
+
+ it("should label each axis from its own setting when both are stored", () => {
+ const { leftAxisModel, rightAxisModel } = getSplitAxesModels({
+ "graph.y_axis.title_text": "Revenue",
+ "graph.y_axis.right.title_text": "Orders",
+ });
+
+ expect(checkNotNull(leftAxisModel).label).toBe("Revenue");
+ expect(checkNotNull(rightAxisModel).label).toBe("Orders");
+ });
+
+ it("should keep the right label when the legend hides every left series", () => {
+ const { leftAxisModel, rightAxisModel } = getYAxesModels(
+ [
+ createMockSeriesModel({ dataKey: LEFT_SERIES_KEY, visible: false }),
+ createMockSeriesModel({ dataKey: RIGHT_SERIES_KEY }),
+ ],
+ dataset,
+ dataset,
+ {
+ series: assignSeriesToAxis,
+ "graph.y_axis.title_text": "Revenue",
+ "graph.y_axis.right.title_text": "Orders",
+ },
+ columnByDataKey,
+ true,
+ [],
+ false,
+ );
+
+ expect(leftAxisModel).toBeNull();
+ expect(checkNotNull(rightAxisModel).label).toBe("Orders");
+ });
+
+ it("should label a right axis with no left axis from 'graph.y_axis.title_text'", () => {
+ const { leftAxisModel, rightAxisModel } = getYAxesModels(
+ seriesModels,
+ dataset,
+ dataset,
+ {
+ series: () => ({ axis: "right" }),
+ "graph.y_axis.title_text": "Shown in the sidebar",
+ "graph.y_axis.right.title_text": "Stale right label",
+ },
+ columnByDataKey,
+ true,
+ [],
+ false,
+ );
+
+ expect(leftAxisModel).toBeNull();
+ expect(checkNotNull(rightAxisModel).label).toBe("Shown in the sidebar");
+ });
+
+ it("should suppress both labels when 'graph.y_axis.labels_enabled' is false", () => {
+ const { leftAxisModel, rightAxisModel } = getSplitAxesModels({
+ "graph.y_axis.labels_enabled": false,
+ "graph.y_axis.title_text": "Revenue",
+ "graph.y_axis.right.title_text": "Orders",
+ });
+
+ expect(checkNotNull(leftAxisModel).label).toBeUndefined();
+ expect(checkNotNull(rightAxisModel).label).toBeUndefined();
+ });
+});
diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/index.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/index.ts
index 26f156f9283..7cd1c8b238f 100644
--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/index.ts
+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/index.ts
@@ -1,6 +1,7 @@
import { isNotNull } from "metabase/utils/types";
import type { RawSeries, SingleSeries } from "metabase-types/api";
+import type { CartesianChartColumns } from "../../../lib/graph/columns";
import {
getCartesianChartColumns,
getReferencedColumns,
@@ -98,19 +99,13 @@ export const getCardsReferencedColumns = (
});
};
-export const getCartesianChartModel = (
+/** The series the chart draws: sorted, capped, and with the tail grouped into "Other". */
+export const getChartSeriesModels = (
rawSeries: RawSeries,
- settings: ComputedVisualizationSettings,
+ cardsColumns: CartesianChartColumns[],
hiddenSeries: string[],
- renderingContext: RenderingContext,
- showWarning?: ShowWarning,
- gridSize?: VisualizationGridSize,
-): CartesianChartModel => {
- // rawSeries has more than one element when two or more cards are combined on a dashboard
- const hasMultipleCards = rawSeries.length > 1;
- const cardsColumns = getCardsColumns(rawSeries, settings);
- const columnByDataKey = getCardsColumnByDataKeyMap(rawSeries, cardsColumns);
- const dimensionModel = getDimensionModel(rawSeries, cardsColumns);
+ settings: ComputedVisualizationSettings,
+) => {
const unsortedSeriesModels = getCardsSeriesModels(
rawSeries,
cardsColumns,
@@ -122,23 +117,12 @@ export const getCartesianChartModel = (
// We display an error message if there are more than 100 series models anyway.
unsortedSeriesModels.splice(101);
- const unsortedDataset = getJoinedCardsDataset(
- rawSeries,
- cardsColumns,
- showWarning,
- );
- const dataset = sortDataset(
- unsortedDataset,
- settings["graph.x_axis.scale"],
- showWarning,
- );
-
+ // rawSeries has more than one element when two or more cards are combined on a dashboard
+ const hasMultipleCards = rawSeries.length > 1;
const sortedSeriesModels = hasMultipleCards
? unsortedSeriesModels
: getSortedSeriesModels(unsortedSeriesModels, settings);
- const scaledDataset = scaleDataset(dataset, sortedSeriesModels, settings);
-
const { ungroupedSeriesModels: seriesModels, groupedSeriesModels } =
groupSeriesIntoOther(sortedSeriesModels, settings);
@@ -154,6 +138,36 @@ export const getCartesianChartModel = (
);
}
+ return { sortedSeriesModels, seriesModels, groupedSeriesModels };
+};
+
+export const getCartesianChartModel = (
+ rawSeries: RawSeries,
+ settings: ComputedVisualizationSettings,
+ hiddenSeries: string[],
+ renderingContext: RenderingContext,
+ showWarning?: ShowWarning,
+ gridSize?: VisualizationGridSize,
+): CartesianChartModel => {
+ const cardsColumns = getCardsColumns(rawSeries, settings);
+ const columnByDataKey = getCardsColumnByDataKeyMap(rawSeries, cardsColumns);
+ const dimensionModel = getDimensionModel(rawSeries, cardsColumns);
+ const { sortedSeriesModels, seriesModels, groupedSeriesModels } =
+ getChartSeriesModels(rawSeries, cardsColumns, hiddenSeries, settings);
+
+ const unsortedDataset = getJoinedCardsDataset(
+ rawSeries,
+ cardsColumns,
+ showWarning,
+ );
+ const dataset = sortDataset(
+ unsortedDataset,
+ settings["graph.x_axis.scale"],
+ showWarning,
+ );
+
+ const scaledDataset = scaleDataset(dataset, sortedSeriesModels, settings);
+
const xAxisModel = getXAxisModel(
dimensionModel,
rawSeries,
diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts b/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts
index f283b8f9492..e5642264bce 100644
--- a/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts
+++ b/frontend/src/metabase/viz-core/echarts/cartesian/model/types.ts
@@ -193,9 +193,14 @@ export type TrendLinesModel = {
seriesModels: TrendLineSeriesModel[];
};
+export type YAxisSide = "left" | "right";
+
+/** Series names on each y-axis, `null` for a side with no axis. */
+export type YAxisSeriesNames = Record<YAxisSide, string[] | null>;
+
export type StackDisplay = "bar" | "area";
export type StackModel = {
- axis: "left" | "right";
+ axis: YAxisSide;
display: StackDisplay;
seriesKeys: DataKey[];
};
diff --git a/frontend/src/metabase/viz-core/lib/settings/graph.ts b/frontend/src/metabase/viz-core/lib/settings/graph.ts
index be7819402e3..cfbe6e65ac8 100644
--- a/frontend/src/metabase/viz-core/lib/settings/graph.ts
+++ b/frontend/src/metabase/viz-core/lib/settings/graph.ts
@@ -6,7 +6,10 @@ import { mergeLazily } from "metabase/utils/merge-lazily";
import { getColumnKey } from "metabase-lib/v1/queries/utils/column-key";
import { isNumeric } from "metabase-lib/v1/types/utils/isa";
import type { Series, VisualizationDisplay } from "metabase-types/api";
+import { isObjectWithRaw } from "metabase-types/guards";
+import { getYAxisLabel } from "../../echarts/cartesian/model/axis";
+import type { YAxisSeriesNames } from "../../echarts/cartesian/model/types";
import {
STACKABLE_SERIES_DISPLAY_TYPES,
getAreDimensionsAndMetricsValid,
@@ -35,6 +38,7 @@ import {
getSeriesOrderDimensionSetting,
getSeriesOrderVisibilitySettings,
getYAxisAutoRangeDefault,
+ getYAxisSeriesNames,
getYAxisUnpinFromZeroDefault,
isShowStackValuesValid,
isStackingValueValid,
@@ -712,6 +716,50 @@ export const GRAPH_COLORS_SETTINGS: VisualizationSettingsDefinitions = {
"graph.colors": {},
};
+// One split per sidebar build: every widget gets the same computed settings.
+const seriesNamesByYAxisCache = new WeakMap<
+ ComputedVisualizationSettings,
+ { series: Series; seriesNames: YAxisSeriesNames }
+>();
+
+// Not `useRawSeries`: it would also change the left label's default.
+const computeSeriesNamesByYAxis = (
+ series: Series,
+ vizSettings: ComputedVisualizationSettings,
+): YAxisSeriesNames => {
+ const rawSeries =
+ isObjectWithRaw(series) && series._raw ? series._raw : series;
+
+ try {
+ return getYAxisSeriesNames(rawSeries, vizSettings);
+ } catch (error) {
+ console.warn("Error computing y-axis series", error);
+ return { left: null, right: null };
+ }
+};
+
+const getSeriesNamesByYAxis = (
+ series: Series,
+ vizSettings: ComputedVisualizationSettings,
+): YAxisSeriesNames => {
+ // Both label fields are hidden, so skip the split.
+ if (vizSettings["graph.y_axis.labels_enabled"] === false) {
+ return { left: null, right: null };
+ }
+
+ const cached = seriesNamesByYAxisCache.get(vizSettings);
+ if (cached?.series === series) {
+ return cached.seriesNames;
+ }
+
+ const seriesNames = computeSeriesNamesByYAxis(series, vizSettings);
+ seriesNamesByYAxisCache.set(vizSettings, { series, seriesNames });
+ return seriesNames;
+};
+
+const isYAxisSplit = ({ left, right }: YAxisSeriesNames) =>
+ left != null && right != null;
+
export const GRAPH_AXIS_SETTINGS: VisualizationSettingsDefinitions = {
"graph.x_axis._is_timeseries": {
readDependencies: ["graph.dimensions"],
@@ -1005,6 +1053,10 @@ export const GRAPH_AXIS_SETTINGS: VisualizationSettingsDefinitions = {
get title() {
return t`Label`;
},
+ getTitle: (series, vizSettings) =>
+ isYAxisSplit(getSeriesNamesByYAxis(series, vizSettings))
+ ? t`Left axis label`
+ : t`Label`,
index: 2,
get group() {
return t`Y-axis`;
@@ -1012,6 +1064,14 @@ export const GRAPH_AXIS_SETTINGS: VisualizationSettingsDefinitions = {
widget: "input",
getHidden: (_series, vizSettings) =>
vizSettings["graph.y_axis.labels_enabled"] === false,
+ // Not in getDefault: the split needs a pass over the rows, and every chart
+ // render computes defaults.
+ getProps: (series, vizSettings) => {
+ const { left, right } = getSeriesNamesByYAxis(series, vizSettings);
+ return {
+ value: getYAxisLabel(left ?? right ?? [], vizSettings, false),
+ };
+ },
getDefault: (series, vizSettings) => {
// If there are multiple series, we check if the metric names match.
// If they do, we use that as the default y axis label.
@@ -1025,6 +1085,28 @@ export const GRAPH_AXIS_SETTINGS: VisualizationSettingsDefinitions = {
},
readDependencies: ["series", "graph.metrics"],
},
+ "graph.y_axis.right.title_text": {
+ getSection: () => t`Axes`,
+ get title() {
+ return t`Right axis label`;
+ },
+ index: 2,
+ get group() {
+ return t`Y-axis`;
+ },
+ widget: "input",
+ getHidden: (series, vizSettings) =>
+ vizSettings["graph.y_axis.labels_enabled"] === false ||
+ !isYAxisSplit(getSeriesNamesByYAxis(series, vizSettings)),
+ // No getDefault: an unset value makes the right axis use the left label.
+ getProps: (series, vizSettings) => ({
+ value: getYAxisLabel(
+ getSeriesNamesByYAxis(series, vizSettings).right ?? [],
+ vizSettings,
+ true,
+ ),
+ }),
+ },
// DEPRECATED" replaced with "label" series setting
"graph.series_labels": {},
};
diff --git a/frontend/src/metabase/viz-core/lib/settings/graph.unit.spec.ts b/frontend/src/metabase/viz-core/lib/settings/graph.unit.spec.ts
index 59cc7d6015f..6ba77264909 100644
--- a/frontend/src/metabase/viz-core/lib/settings/graph.unit.spec.ts
+++ b/frontend/src/metabase/viz-core/lib/settings/graph.unit.spec.ts
@@ -267,9 +267,103 @@ describe("GRAPH_AXIS_SETTINGS", () => {
},
);
});
-});
-describe("GRAPH_TREND_SETTINGS", () => {
+ describe("the y-axis label fields", () => {
+ const isLeftLabelHidden = checkNotNull(
+ GRAPH_AXIS_SETTINGS["graph.y_axis.title_text"]?.getHidden,
+ );
+ const isRightLabelHidden = checkNotNull(
+ GRAPH_AXIS_SETTINGS["graph.y_axis.right.title_text"]?.getHidden,
+ );
+
+ const MONTH_COLUMN = "month";
+ const REVENUE_COLUMN = "revenue";
+ const ORDERS_COLUMN = "orders";
+
+ // Revenue and orders live on ranges three orders of magnitude apart, which
+ // is what makes the automatic split kick in.
+ const createTwoMetricSeries = () => [
+ createMockSingleSeries(
+ createMockCard({ display: "line" }),
+ createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({
+ name: MONTH_COLUMN,
+ display_name: "Month",
+ base_type: "type/Text",
+ }),
+ createMockColumn({
+ name: REVENUE_COLUMN,
+ display_name: "Revenue",
+ base_type: "type/Number",
+ }),
+ createMockColumn({
+ name: ORDERS_COLUMN,
+ display_name: "Orders",
+ base_type: "type/Number",
+ }),
+ ],
+ rows: [
+ ["Jan", 1, 900],
+ ["Feb", 2, 1000],
+ ],
+ }),
+ }),
+ ),
+ ];
+
+ const splitSettings = {
+ "graph.dimensions": [MONTH_COLUMN],
+ "graph.metrics": [REVENUE_COLUMN, ORDERS_COLUMN],
+ "graph.y_axis.auto_split": true,
+ };
+
+ it.each([
+ {
+ name: "a single-metric chart",
+ settings: { ...splitSettings, "graph.metrics": [REVENUE_COLUMN] },
+ },
+ {
+ // The only axis is on the right, and the shared field labels it.
+ name: "a chart with every series pinned right",
+ settings: {
+ ...splitSettings,
+ "graph.y_axis.auto_split": false,
+ series: () => ({ axis: "right" as const }),
+ },
+ },
+ {
+ // Split panels draw one shared label from the left axis model.
+ name: "split panels",
+ settings: { ...splitSettings, "graph.split_panels": true },
+ },
+ ])("should offer only the shared label for $name", ({ settings }) => {
+ const series = createTwoMetricSeries();
+
+ expect(isLeftLabelHidden(series, settings)).toBe(false);
+ expect(isRightLabelHidden(series, settings)).toBe(true);
+ });
+
+ it("should offer both labels when the chart splits its y-axis", () => {
+ const series = createTwoMetricSeries();
+
+ expect(isLeftLabelHidden(series, splitSettings)).toBe(false);
+ expect(isRightLabelHidden(series, splitSettings)).toBe(false);
+ });
+
+ it("should hide both when y-axis labels are turned off", () => {
+ const settings = {
+ ...splitSettings,
+ "graph.y_axis.labels_enabled": false,
+ };
+ const series = createTwoMetricSeries();
+
+ expect(isLeftLabelHidden(series, settings)).toBe(true);
+ expect(isRightLabelHidden(series, settings)).toBe(true);
+ });
+ });
+
describe("graph.show_trendline", () => {
const getHidden = checkNotNull(
GRAPH_TREND_SETTINGS["graph.show_trendline"]?.getHidden,
diff --git a/frontend/src/metabase/viz-core/lib/widgets.ts b/frontend/src/metabase/viz-core/lib/widgets.ts
index 200ba38c339..5bf05efec01 100644
--- a/frontend/src/metabase/viz-core/lib/widgets.ts
+++ b/frontend/src/metabase/viz-core/lib/widgets.ts
@@ -66,12 +66,16 @@ function getSettingWidget<T, TValue, TProps extends Record<string, unknown>>(
getWrapperStyle,
getSection,
getHidden,
+ getTitle,
...settingDefProps
} = settingDef;
return {
...settingDefProps,
id: settingId,
+ title:
+ getTitle?.(resolvedObject, computedSettings, extra) ??
+ settingDefProps.title,
value,
section: getSection?.(resolvedObject, computedSettings, extra),
hidden: getHidden?.(resolvedObject, computedSettings, extra) ?? false,
diff --git a/frontend/src/metabase/viz-core/shared/settings/cartesian-chart.ts b/frontend/src/metabase/viz-core/shared/settings/cartesian-chart.ts
index ace69696361..bb39b686ad1 100644
--- a/frontend/src/metabase/viz-core/shared/settings/cartesian-chart.ts
+++ b/frontend/src/metabase/viz-core/shared/settings/cartesian-chart.ts
@@ -18,11 +18,21 @@ import type {
VisualizationDisplay,
} from "metabase-types/api";
+import { getBoxPlotModel } from "../../echarts/boxplot/model";
import {
getCardsColumns,
getCardsReferencedColumns,
+ getChartSeriesModels,
} from "../../echarts/cartesian/model";
+import { getYAxisSplit } from "../../echarts/cartesian/model/axis";
+import { getJoinedCardsDataset } from "../../echarts/cartesian/model/dataset";
import { getCardsSeriesModels } from "../../echarts/cartesian/model/series";
+import { getStackModels } from "../../echarts/cartesian/model/stack";
+import type {
+ DataKey,
+ YAxisSeriesNames,
+} from "../../echarts/cartesian/model/types";
+import { hasValidColumnsSelected } from "../../lib/graph/columns";
import {
getMaxDimensionsSupported,
getMaxMetricsSupported,
@@ -277,6 +287,84 @@ export const getDefaultIsHistogram = (dimensionColumn: DatasetColumn) => {
export const getDefaultIsAutoSplitEnabled = () => true;
+const getSeriesNamesBySide = (
+ seriesModels: { dataKey: DataKey; name: string }[],
+ leftAxisSeriesKeys: Set<DataKey>,
+ rightAxisSeriesKeys: Set<DataKey>,
+): YAxisSeriesNames => {
+ const getNames = (keys: Set<DataKey>) =>
+ keys.size > 0
+ ? seriesModels
+ .filter(({ dataKey }) => keys.has(dataKey))
+ .map(({ name }) => name)
+ : null;
+
+ return {
+ left: getNames(leftAxisSeriesKeys),
+ right: getNames(rightAxisSeriesKeys),
+ };
+};
+
+/** Series names on each y-axis, split the way the renderer splits them. */
+export function getYAxisSeriesNames(
+ rawSeries: RawSeries,
+ settings: ComputedVisualizationSettings,
+): YAxisSeriesNames {
+ const [firstSeries] = rawSeries;
+
+ if (
+ firstSeries == null ||
+ !hasValidColumnsSelected(settings, firstSeries.data)
+ ) {
+ return { left: null, right: null };
+ }
+
+ const display = firstSeries.card.display;
+
+ // A waterfall has one axis and no automatic label.
+ if (display === "waterfall") {
+ return { left: [], right: null };
+ }
+
+ // Box plots split on the extents of the computed boxes.
+ if (display === "boxplot") {
+ const { seriesModels, leftAxisSeriesKeys, rightAxisSeriesKeys } =
+ getBoxPlotModel(rawSeries, settings);
+ return getSeriesNamesBySide(
+ seriesModels,
+ leftAxisSeriesKeys,
+ rightAxisSeriesKeys,
+ );
+ }
+
+ const cardsColumns = getCardsColumns(rawSeries, settings);
+ const { seriesModels } = getChartSeriesModels(
+ rawSeries,
+ cardsColumns,
+ [],
+ settings,
+ );
+ const stackModels = getStackModels(seriesModels, settings);
+
+ // Scatter plots never auto-split, see `getScatterPlotModel`.
+ const isAutoSplitSupported = display !== "scatter";
+
+ const [leftAxisSeriesKeys, rightAxisSeriesKeys] = getYAxisSplit(
+ seriesModels,
+ stackModels,
+ // Unsorted is fine: sorting doesn't change a min or a max.
+ getJoinedCardsDataset(rawSeries, cardsColumns),
+ settings,
+ isAutoSplitSupported,
+ );
+
+ return getSeriesNamesBySide(
+ seriesModels,
+ leftAxisSeriesKeys,
+ rightAxisSeriesKeys,
+ );
+}
+
export const getDefaultXAxisScale = (
vizSettings: ComputedVisualizationSettings,
display?: string,
diff --git a/frontend/src/metabase/viz-core/shared/settings/cartesian-chart.unit.spec.ts b/frontend/src/metabase/viz-core/shared/settings/cartesian-chart.unit.spec.ts
index e4222f2f257..58ac80493f5 100644
--- a/frontend/src/metabase/viz-core/shared/settings/cartesian-chart.unit.spec.ts
+++ b/frontend/src/metabase/viz-core/shared/settings/cartesian-chart.unit.spec.ts
@@ -1,16 +1,32 @@
-import type { DatasetData, VisualizationDisplay } from "metabase-types/api";
+import type {
+ DatasetData,
+ RawSeries,
+ VisualizationDisplay,
+} from "metabase-types/api";
import {
createMockCard,
createMockColumn,
+ createMockDataset,
createMockDatasetData,
createMockSingleSeries,
} from "metabase-types/api/mocks";
+import { getBoxPlotModel } from "../../echarts/boxplot/model";
+import { getCartesianChartModel } from "../../echarts/cartesian/model";
+import type { LegacySeriesSettingsObjectKey } from "../../echarts/cartesian/model/types";
+import { getScatterPlotModel } from "../../echarts/cartesian/scatter/model";
+import type {
+ ComputedVisualizationSettings,
+ RenderingContext,
+} from "../../types";
+import { DEFAULT_VISUALIZATION_THEME } from "../utils/theme";
+
import {
getDefaultBoxplotDimensions,
getDefaultColumns,
getDefaultDimensions,
getDefaultMetrics,
+ getYAxisSeriesNames,
} from "./cartesian-chart";
const createSeries = ({
@@ -277,3 +293,306 @@ describe("getDefaultBoxplotDimensions", () => {
expect(result).toEqual(["status"]);
});
});
+
+describe("getYAxisSeriesNames", () => {
+ const getYAxisSides = (
+ rawSeries: RawSeries,
+ settings: ComputedVisualizationSettings,
+ ) => {
+ const { left, right } = getYAxisSeriesNames(rawSeries, settings);
+ return { left: left != null, right: right != null };
+ };
+
+ const MONTH = "month";
+ const CATEGORY = "category";
+ const REVENUE = "revenue";
+ const ORDERS = "orders";
+
+ const renderingContext: RenderingContext = {
+ getColor: (name) => name,
+ measureText: () => 10,
+ measureTextHeight: () => 10,
+ fontFamily: "Arial",
+ theme: DEFAULT_VISUALIZATION_THEME,
+ };
+
+ // The real computed settings always carry the per-series accessor; the chart
+ // model reads each series' display through it.
+ const lineSeries = () => ({ display: "line" as const });
+
+ const pinnedRight =
+ (...keys: string[]) =>
+ ({ card }: LegacySeriesSettingsObjectKey) =>
+ keys.includes(String(card._seriesKey))
+ ? { ...lineSeries(), axis: "right" as const }
+ : lineSeries();
+
+ const createTwoMetricSeries = (
+ rows: DatasetData["rows"],
+ display: VisualizationDisplay = "line",
+ ): RawSeries => [
+ createMockSingleSeries(
+ createMockCard({ display }),
+ createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({ name: MONTH, base_type: "type/Text" }),
+ createMockColumn({ name: REVENUE, base_type: "type/Number" }),
+ createMockColumn({ name: ORDERS, base_type: "type/Number" }),
+ ],
+ rows,
+ }),
+ }),
+ ),
+ ];
+
+ const createBreakoutSeries = (): RawSeries => [
+ createMockSingleSeries(
+ createMockCard({ display: "line" }),
+ createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({ name: MONTH, base_type: "type/Text" }),
+ createMockColumn({ name: CATEGORY, base_type: "type/Text" }),
+ createMockColumn({ name: ORDERS, base_type: "type/Number" }),
+ ],
+ rows: [
+ ["Jan", "a", 1],
+ ["Jan", "b", 10],
+ ["Jan", "c", 10000],
+ ["Feb", "a", 2],
+ ["Feb", "b", 20],
+ ["Feb", "c", 20000],
+ ],
+ }),
+ }),
+ ),
+ ];
+
+ const twoMetricSettings = {
+ "graph.dimensions": [MONTH],
+ "graph.metrics": [REVENUE, ORDERS],
+ "graph.y_axis.auto_split": true,
+ series: lineSeries,
+ };
+
+ const breakoutSettings = {
+ "graph.dimensions": [MONTH, CATEGORY],
+ "graph.metrics": [ORDERS],
+ "graph.y_axis.auto_split": true,
+ series: lineSeries,
+ };
+
+ const divergentRows = [
+ ["Jan", 1, 900],
+ ["Feb", 2, 1000],
+ ];
+
+ const similarRows = [
+ ["Jan", 900, 950],
+ ["Feb", 1000, 1100],
+ ];
+
+ // The sidebar decides which axis label fields to offer and the renderer
+ // decides which axes to draw, through different code. A disagreement either
+ // hides the setting for an axis that exists or offers one for an axis that
+ // does not.
+ it.each([
+ {
+ name: "two metrics on ranges far apart",
+ sides: { left: true, right: true },
+ rawSeries: createTwoMetricSeries(divergentRows),
+ settings: twoMetricSettings,
+ },
+ {
+ name: "two metrics on similar ranges",
+ sides: { left: true, right: false },
+ rawSeries: createTwoMetricSeries(similarRows),
+ settings: twoMetricSettings,
+ },
+ {
+ name: "the automatic split turned off",
+ sides: { left: true, right: false },
+ rawSeries: createTwoMetricSeries(divergentRows),
+ settings: { ...twoMetricSettings, "graph.y_axis.auto_split": false },
+ },
+ {
+ name: "a single metric",
+ sides: { left: true, right: false },
+ rawSeries: createTwoMetricSeries(divergentRows),
+ settings: { ...twoMetricSettings, "graph.metrics": [REVENUE] },
+ },
+ {
+ name: "one series pinned to the right axis",
+ sides: { left: true, right: true },
+ rawSeries: createTwoMetricSeries(similarRows),
+ settings: {
+ ...twoMetricSettings,
+ "graph.y_axis.auto_split": false,
+ series: pinnedRight(ORDERS),
+ },
+ },
+ {
+ name: "every series pinned to the right axis, leaving no left axis",
+ sides: { left: false, right: true },
+ rawSeries: createTwoMetricSeries(similarRows),
+ settings: {
+ ...twoMetricSettings,
+ "graph.y_axis.auto_split": false,
+ series: pinnedRight(REVENUE, ORDERS),
+ },
+ },
+ {
+ name: "every breakout series pinned to the right axis",
+ sides: { left: false, right: true },
+ rawSeries: createBreakoutSeries(),
+ settings: { ...breakoutSettings, series: pinnedRight("a", "b", "c") },
+ },
+ {
+ name: "split panels",
+ sides: { left: true, right: false },
+ rawSeries: createTwoMetricSeries(divergentRows),
+ settings: { ...twoMetricSettings, "graph.split_panels": true },
+ },
+ {
+ name: "stacked bars",
+ sides: { left: true, right: false },
+ rawSeries: createTwoMetricSeries(divergentRows, "bar"),
+ settings: {
+ ...twoMetricSettings,
+ series: () => ({ display: "bar" as const }),
+ "stackable.stack_type": "stacked" as const,
+ },
+ },
+ {
+ name: "a breakout, where one metric column means no automatic split",
+ sides: { left: true, right: false },
+ rawSeries: createBreakoutSeries(),
+ settings: breakoutSettings,
+ },
+ {
+ name: "a breakout series pinned right, then grouped into Other",
+ sides: { left: true, right: false },
+ rawSeries: createBreakoutSeries(),
+ settings: {
+ ...breakoutSettings,
+ "graph.max_categories_enabled": true,
+ "graph.max_categories": 2,
+ series: pinnedRight("c"),
+ },
+ },
+ ])(
+ "agrees with the axes the chart model builds for $name",
+ ({ rawSeries, settings, sides }) => {
+ const chartModel = getCartesianChartModel(
+ rawSeries,
+ settings,
+ [],
+ renderingContext,
+ );
+
+ expect({
+ left: chartModel.leftAxisModel != null,
+ right: chartModel.rightAxisModel != null,
+ }).toEqual(sides);
+ expect(getYAxisSides(rawSeries, settings)).toEqual(sides);
+ },
+ );
+
+ it("reports no axes when the chart plots nothing", () => {
+ expect(getYAxisSides([], {})).toEqual({ left: false, right: false });
+ });
+
+ it.each([
+ { name: "no dimension", settings: { "graph.dimensions": [] } },
+ { name: "no metric", settings: { "graph.metrics": [] } },
+ ])(
+ "reports no axes for a chart that cannot render yet, with $name",
+ ({ settings }) => {
+ expect(
+ getYAxisSides(createTwoMetricSeries(divergentRows), {
+ ...twoMetricSettings,
+ ...settings,
+ }),
+ ).toEqual({ left: false, right: false });
+ },
+ );
+
+ it("reports a left axis only for a waterfall, which never builds a right one", () => {
+ expect(
+ getYAxisSides(createTwoMetricSeries(divergentRows, "waterfall"), {
+ ...twoMetricSettings,
+ "graph.metrics": [REVENUE],
+ }),
+ ).toEqual({ left: true, right: false });
+ });
+
+ it.each([
+ {
+ name: "two metrics on ranges far apart",
+ sides: { left: true, right: true },
+ settings: twoMetricSettings,
+ },
+ {
+ name: "the automatic split turned off",
+ sides: { left: true, right: false },
+ settings: { ...twoMetricSettings, "graph.y_axis.auto_split": false },
+ },
+ {
+ name: "every series pinned to the right axis",
+ sides: { left: false, right: true },
+ settings: {
+ ...twoMetricSettings,
+ "graph.y_axis.auto_split": false,
+ series: pinnedRight(REVENUE, ORDERS),
+ },
+ },
+ ])(
+ "agrees with the axes the box plot model builds for $name",
+ ({ settings, sides }) => {
+ const rawSeries = createTwoMetricSeries(divergentRows, "boxplot");
+ const chartModel = getBoxPlotModel(rawSeries, settings);
+
+ expect({
+ left: chartModel.leftAxisModel != null,
+ right: chartModel.rightAxisModel != null,
+ }).toEqual(sides);
+ expect(getYAxisSides(rawSeries, settings)).toEqual(sides);
+ },
+ );
+
+ it.each([
+ {
+ name: "two metrics on ranges far apart, which never split on their own",
+ sides: { left: true, right: false },
+ settings: twoMetricSettings,
+ },
+ {
+ name: "one series pinned to the right axis",
+ sides: { left: true, right: true },
+ settings: { ...twoMetricSettings, series: pinnedRight(ORDERS) },
+ },
+ {
+ name: "every series pinned to the right axis",
+ sides: { left: false, right: true },
+ settings: { ...twoMetricSettings, series: pinnedRight(REVENUE, ORDERS) },
+ },
+ ])(
+ "agrees with the axes the scatter plot model builds for $name",
+ ({ settings, sides }) => {
+ const rawSeries = createTwoMetricSeries(divergentRows, "scatter");
+ const chartModel = getScatterPlotModel(
+ rawSeries,
+ settings,
+ [],
+ renderingContext,
+ );
+
+ expect({
+ left: chartModel.leftAxisModel != null,
+ right: chartModel.rightAxisModel != null,
+ }).toEqual(sides);
+ expect(getYAxisSides(rawSeries, settings)).toEqual(sides);
+ },
+ );
+});
diff --git a/frontend/src/metabase/viz-core/types/definition.ts b/frontend/src/metabase/viz-core/types/definition.ts
index 095d6ae19b2..71936549f30 100644
--- a/frontend/src/metabase/viz-core/types/definition.ts
+++ b/frontend/src/metabase/viz-core/types/definition.ts
@@ -109,6 +109,13 @@ export type VisualizationSettingDefinition<
: ComputedVisualizationSettings,
extra?: SettingsExtra,
) => string | undefined;
+ getTitle?: (
+ object: T,
+ settings: T extends DatasetColumn
+ ? ColumnSettings
+ : ComputedVisualizationSettings,
+ extra?: SettingsExtra,
+ ) => string;
getWrapperStyle?: (
object: T,
settings: T extends DatasetColumn
@@ -146,7 +153,7 @@ export type CompleteVisualizationSettingDefinition<
TProps extends Record<string, unknown> = Record<string, unknown>,
> = Omit<
VisualizationSettingDefinition<T, TValue, TProps>,
- "getProps" | "getWrapperStyle" | "getHidden" | "getSection"
+ "getProps" | "getWrapperStyle" | "getHidden" | "getSection" | "getTitle"
> & {
id: string;
style?: CSSProperties;
@@ -271,6 +278,7 @@ export type VisualizationSettingsDefinitions = {
"graph.y_axis.max"?: SeriesSettingDefinition<Value, Props>;
"graph.y_axis.min"?: SeriesSettingDefinition<Value, Props>;
"graph.y_axis.axis_enabled"?: SeriesSettingDefinition<Value, Props>;
+ "graph.y_axis.right.title_text"?: SeriesSettingDefinition<Value, Props>;
"graph.y_axis.scale"?: SeriesSettingDefinition<Value, Props>;
"graph.y_axis.split_number"?: SeriesSettingDefinition<Value, Props>;
"graph.y_axis.title_text"?: SeriesSettingDefinition<Value, Props>;
diff --git a/resources/mcp/v2/skills/visualization-settings/references/settings.md b/resources/mcp/v2/skills/visualization-settings/references/settings.md
index effde96d97c..9c266a53398 100644
--- a/resources/mcp/v2/skills/visualization-settings/references/settings.md
+++ b/resources/mcp/v2/skills/visualization-settings/references/settings.md
@@ -22,7 +22,7 @@ Goal & trend: `graph.show_goal` (bool), `graph.goal_value` (number), `graph.goal
Data labels: `graph.show_values` (bool), `graph.label_value_frequency` (`"fit"`/`"all"`), `graph.show_stack_values` (`"total"`/`"series"`/`"all"`, stacked bars), `graph.label_value_formatting` (`"auto"`/`"compact"`/`"full"`).
-Axes: `graph.x_axis.scale` (`"timeseries"` `"linear"` `"pow"` `"log"` `"histogram"` `"ordinal"`), `graph.y_axis.scale` (`"linear"` `"pow"` `"log"`), `graph.x_axis.axis_enabled` (`true`/`false`/`"compact"`/`"rotate-45"`/`"rotate-90"`), `graph.y_axis.axis_enabled` (bool), `graph.y_axis.auto_range` (bool) with `graph.y_axis.min`/`.max`, `graph.y_axis.unpin_from_zero` (bool), `graph.y_axis.auto_split` (bool), `graph.x_axis.title_text` / `graph.y_axis.title_text`.
+Axes: `graph.x_axis.scale` (`"timeseries"` `"linear"` `"pow"` `"log"` `"histogram"` `"ordinal"`), `graph.y_axis.scale` (`"linear"` `"pow"` `"log"`), `graph.x_axis.axis_enabled` (`true`/`false`/`"compact"`/`"rotate-45"`/`"rotate-90"`), `graph.y_axis.axis_enabled` (bool), `graph.y_axis.auto_range` (bool) with `graph.y_axis.min`/`.max`, `graph.y_axis.unpin_from_zero` (bool), `graph.y_axis.auto_split` (bool), `graph.x_axis.title_text` / `graph.y_axis.title_text`, and `graph.y_axis.right.title_text` for the right axis of a split chart (unset or blank falls back to `graph.y_axis.title_text`).
Tooltip: `graph.tooltip_columns` (string[] — extra columns on hover).