Skip to content

Commit

Permalink
[FIX] chart: center pyramid charts vertical axis
Browse files Browse the repository at this point in the history
The vertical axis should be centered in pyramid chart so we can easily
compare the values of the left and right sides.

closes #5218

Task: 4334617
Signed-off-by: Lucas Lefèvre (lul) <[email protected]>
  • Loading branch information
hokolomopo committed Nov 25, 2024
1 parent a5e4e16 commit 45f954a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
6 changes: 6 additions & 0 deletions src/helpers/figures/charts/pyramid_chart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,15 @@ export function createPyramidChartRuntime(
datasets[1].data = datasets[1].data.map((value: number) => (value > 0 ? -value : 0));
}

const maxValue = Math.max(
...config.data?.datasets.map((dataSet) => Math.max(...dataSet.data.map(Math.abs)))
);

const scales = config.options!.scales;
const scalesXCallback = scales!.x!.ticks!.callback as (value: number) => string;
scales!.x!.ticks!.callback = (value: number) => scalesXCallback(Math.abs(value));
scales!.x!.suggestedMin = -maxValue;
scales!.x!.suggestedMax = maxValue;

const tooltipLabelCallback = config.options!.plugins!.tooltip!.callbacks!.label! as any;
config.options!.plugins!.tooltip!.callbacks!.label = (item) => {
Expand Down
21 changes: 20 additions & 1 deletion tests/figures/chart/pyramid_chart_plugin.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ChartCreationContext, Model } from "../../../src";
import { ChartCreationContext, ChartJSRuntime, Model } from "../../../src";
import { PyramidChart } from "../../../src/helpers/figures/charts/pyramid_chart";
import { PyramidChartDefinition } from "../../../src/types/chart/pyramid_chart";
import { createChart, setCellContent, setFormat } from "../../test_helpers/commands_helpers";
Expand Down Expand Up @@ -101,5 +101,24 @@ describe("population pyramid chart", () => {
const tooltip = runtime.chartJsConfig.options?.plugins?.tooltip as any;
expect(tooltip?.callbacks?.label(tooltipTestItem)).toBe("dataSetLabel: 10€");
});

test("The negative and positive values have the same max value", () => {
setCellContent(model, "A1", "5");
setCellContent(model, "A2", "33");

createChart(
model,
{
type: "pyramid",
dataSets: [{ dataRange: "A1" }, { dataRange: "A2" }],
dataSetsHaveTitle: false,
},
"id"
);
const runtime = model.getters.getChartRuntime("id") as ChartJSRuntime;
const options = runtime.chartJsConfig.options;
expect(options?.scales?.x?.suggestedMin).toBe(-33);
expect(options?.scales?.x?.suggestedMax).toBe(33);
});
});
});

0 comments on commit 45f954a

Please sign in to comment.