How to calculate the value axis range based on the visible data points in the cartesian chart (SfCartesianChart)?
In this article, we explain how to calculate the value axis range based on the visible data points in Flutter Cartesian chart.
In the SfCartesianChart widget, we can control the range of the value axis by using the anchorRangeToVisiblePoints property. It is applicable for value axes only. If we set anchorRangeToVisiblePoints as false, the y axis range is calculated for the overall data points available in the data source. If we set anchorRangeToVisiblePoints as true, the value axis range will be calculated for the data points available in the viewport. By default, the anchorRangeToVisiblePoints is true.
The following steps explain how to represent the y axis range by considering the visible data points on panning in the SfCartesianChart widget.
Step 1: Initialize the chartData variable which holds the data source for the chart.
late List<_ChartData> chartData;
@override
void initState() {
chartData = <_ChartData>[
_ChartData(1, 10),
_ChartData(2, 20),
_ChartData(3, 30),
_ChartData(4, 40),
_ChartData(5, 50),
_ChartData(6, 60),
_ChartData(7, 70),
_ChartData(8, 80),
_ChartData(9, 90),
_ChartData(10, 100)
];
super.initState();
}
class _ChartData {
_ChartData(this.x, this.y);
final int x;
final int y;
}
Step 2: Now create the SfCartesianChart widget with the ColumnSeries and assign the chartData to the dataSource property and map the x, y values to xValueMapper, yValueMapper properties respectively.
SfCartesianChart(
series: <ColumnSeries<_ChartData, int>>[
ColumnSeries<_ChartData, int>(
dataSource: chartData,
xValueMapper: (_ChartData data, _) => data.x,
yValueMapper: (_ChartData data, _) => data.y
),
],
)
Step 3: Set initialVisibleMinimum and initialVisibleMaximum for the x-axis. Enable the panning and set zoomMode as ZoomMode.x in zoompanBehavior.
late ZoomPanBehavior _zoomPanBehavior;
@override
void initState() {
_zoomPanBehavior = ZoomPanBehavior(
enablePanning: true,
zoomMode: ZoomMode.x
);
super.initState();
}
SfCartesianChart(
primaryXAxis: NumericAxis(
initialVisibleMinimum: 2,
initialVisibleMaximum: 6,
),
primaryYAxis: NumericAxis(
anchorRangeToVisiblePoints: true
),
zoomPanBehavior: _zoomPanBehavior,
series: <ColumnSeries<ChartData, int>>[
ColumnSeries<ChartData, int>(
dataSource: chartData,
xValueMapper: (ChartData data, _) => data.x,
yValueMapper: (ChartData data, _) => data.y
),
]
)
On panning the chart, depending on the y-value the y-axis range can be changed as shown in the below image.