How to jitter the data points of the scatter series in Flutter Cartesian Chart (SfCartesianChart) ?
In this article, we explain how to jitter the data points of the scatter series using Flutter Cartesian chart.
The SfCartesianChart widget has ScatterSeries support and when multiple y-values are assigned to the same x-value, plotting the scatter series can look cluttered. This can be improved by adding a jittering effect to the rendering points.
The following steps explain how to jitter the data points of the ScatterSeries in the SfCartesianChart widget.
Step 1: Initialize the chartData variable that holds the data source.
late List<SampleData> chartData;
Step 2: Create the SfCartesianChart widget with the ScatterSeries, assign the chartData to the dataSource property and initialize chart with other required properties.
SfCartesianChart( primaryYAxis: NumericAxis(interval: 10), primaryXAxis: NumericAxis(interval: 2, minimum: 0, maximum: 11), series: <ScatterSeries<SampleData, num>>[ ScatterSeries( markerSettings: const MarkerSettings(width: 5, height: 5), dataSource: chartData, xValueMapper: (SampleData data, _) => data.x, yValueMapper: (SampleData data, _) => data.y) ], )
Step 3: Create a getData method for generating jitter data. In this method, we have applied a formula which can be found in below code snippet to find the jitter value for x-values.
List<SampleData> getData() { final List<SampleData> data = []; for (int i = 1; i <= 10; i++) { for (int j = 0; j < 25; j++) { //Formula to find the jitter value final double jitterValue = (Random().nextDouble() - 0.5) * 0.3; data.add(SampleData( i + jitterValue, getRandomData(1, 40) + Random().nextDouble())); } } return data; } int getRandomData(int min, int max) { return min + Random().nextInt(max - min); } @override void initState() { chartData = getData(); super.initState(); }
Thus, the scatter series with the jitter data point is achieved.