Open In App

How to Create a Scatter Chart in Android to Represent Data?

Last Updated : 03 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

If you are looking to show a huge quantity of data and you are searching for a different UI design for the representation of this type of view. Then you can represent this view using a scatter chart. A Scatter chart is used to represent data. By using this scatter chart you can easily represent data in scattered form. In this article, we will see the implementation of the Scatter Chart in Android. 

What we are going to build in this article? 

We will be building a simple chart in which we will be displaying a chart in which we will be displaying data. A sample GIF is given below to get an idea about what we are going to do in this article.

Note that we are going to implement this project using the Java language. 

Scatter


Important Attributes of Scattered Chart

Attribute

Uses

setDrawGridBackgroundThis method is use to set the background to the grid.
setTouchEnabledThis method is used to enable gestures on our charts.
setMaxHighlightDistanceSets the maximum distance in screen dp a touch can be away from an entry to cause it to get highlighted.
setDragEnabledThis method is used to enable and disable dragging.
setScaleEnabledThis method is used to enable scaling. 
setMaxVisibleValueCountSets the number of maximum visible drawn values on the chart only active when setDrawValues() is enabled
setPinchZoomIt is used to scale both the x and the y-axis with zoom. 
getLegendThis method is used to get the legend of the chart.
getAxisLeftReturns left y-axis object.
getAxisRightReturns right y-axis object.
setDrawGridLinesThis method is used to draw grid lines. 
setScatterShapeSets the ScatterShape this DataSet should be drawn with. This will search for an available IShapeRenderer and set this renderer for the DataSet.
setDataSets new data objects for our chart.
invalidateThis method is used to invalidate the view if the view is enabled.


Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add dependency to build.gradle(Module:app)

Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.   

implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

After adding this navigate to the build.gradle (Project) and add the below line to it inside the repositories section. 

allprojects {
   repositories {
       // add below line in repositories section
       maven { url 'https://jitpack.io' }
       google()
       centre()
    }
}


Step 3: Working with the activity_main.xml file

Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".MainActivity">

    <!--Ui component for our bar chart-->
    <com.github.mikephil.charting.charts.ScatterChart
        android:id="@+id/chart_layout"
        android:layout_width="350sp"
        android:layout_height="700sp"
        app:layout_constraintBottom_toTopOf="@+id/refresh"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/refresh"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Refresh"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chart_layout" />

</androidx.constraintlayout.widget.ConstraintLayout>

Design Output:

ScatterChart


Step 4: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

MainActivity.java:

package com.gfg.scatter_bar;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private ScatterChart scatterChart;
    private Button refreshButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize the scatter chart and button
        scatterChart = findViewById(R.id.chart_layout);
        refreshButton = findViewById(R.id.refresh);

        configureChartAppearance();
        setupChartData();

        // Set up the button click listener
        refreshButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetChart();
            }
        });
    }

    private void configureChartAppearance() {
        // Disable the description of the scatter chart
        scatterChart.getDescription().setEnabled(false);
        scatterChart.setDrawGridBackground(false);
        scatterChart.setTouchEnabled(true);
        scatterChart.setMaxHighlightDistance(50f);
        scatterChart.setDragEnabled(true);
        scatterChart.setScaleEnabled(true);
        scatterChart.setMaxVisibleValueCount(200);
        scatterChart.setPinchZoom(true);

        // Configure the legend
        Legend legend = scatterChart.getLegend();
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setOrientation(Legend.LegendOrientation.VERTICAL);
        legend.setDrawInside(false);
        legend.setXOffset(5f);

        // Configure the Y-axis
        YAxis leftAxis = scatterChart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);
        
        // Disable the right Y-axis
        scatterChart.getAxisRight().setEnabled(false); 

        // Configure the X-axis
        XAxis xAxis = scatterChart.getXAxis();
        xAxis.setDrawGridLines(false);
        
        // Set granularity to 1 for better spacing
        xAxis.setGranularity(1f); 
        
        // Set the maximum value for the X-axis
        xAxis.setAxisMaximum(70f); 
    }

    private void setupChartData() {
        
        // Create data sets for the scatter chart
        // with increased distance
        ArrayList<Entry> dataSet1Entries = createDataSetEntries(0, 11, 5); 
        ArrayList<Entry> dataSet2Entries = createDataSetEntries(11, 21, 6); 
        ArrayList<Entry> dataSet3Entries = createDataSetEntries(21, 31, 7);

        // Create scatter data sets
        ScatterDataSet dataSet1 = createScatterDataSet(dataSet1Entries, "Point 1",
                ScatterChart.ScatterShape.SQUARE, ColorTemplate.COLORFUL_COLORS[0]);
        
        ScatterDataSet dataSet2 = createScatterDataSet(dataSet2Entries, "Point 2",
                ScatterChart.ScatterShape.CIRCLE, ColorTemplate.COLORFUL_COLORS[1]);
        
        dataSet2.setScatterShapeHoleColor(ColorTemplate.COLORFUL_COLORS[3]);
        dataSet2.setScatterShapeHoleRadius(3f);

        ScatterDataSet dataSet3 = createScatterDataSet(dataSet3Entries, "Point 3",
                ScatterChart.ScatterShape.CIRCLE, ColorTemplate.COLORFUL_COLORS[2]);

        // Set the size for scatter shapes
        float scatterShapeSize = 10f; // Slightly larger for better visibility
        dataSet1.setScatterShapeSize(scatterShapeSize);
        dataSet2.setScatterShapeSize(scatterShapeSize);
        dataSet3.setScatterShapeSize(scatterShapeSize);

        // Create a list of data sets and set it to the chart
        ArrayList<IScatterDataSet> dataSets = new ArrayList<>();
        dataSets.add(dataSet1);
        dataSets.add(dataSet2);
        dataSets.add(dataSet3);

        ScatterData scatterData = new ScatterData(dataSets);
        scatterData.setValueTextSize(10f);
        scatterChart.setData(scatterData);
        
        // Refresh the chart
        scatterChart.invalidate(); 
    }

    private void resetChart() {
        
        // Reset the chart data
        scatterChart.clear();
        
        // Re-setup the chart data
        setupChartData(); 

        // Zoom out the chart
        scatterChart.fitScreen();
    }

    private ArrayList<Entry> createDataSetEntries(int start, int end, int multiplier) {
        ArrayList<Entry> entries = new ArrayList<>();
        for (int i = start; i < end; i++) {
            // Increase the distance between points by adjusting the Y value
            entries.add(new Entry(i * 2, i * multiplier)); 
        }
        return entries;
    }

    private ScatterDataSet createScatterDataSet(ArrayList<Entry> entries,
                String label, ScatterChart.ScatterShape shape, int color) 
        {
        ScatterDataSet dataSet = new ScatterDataSet(entries, label);
        dataSet.setScatterShape(shape);
        dataSet.setColor(color);
        return dataSet;
    }
}


After adding the above code now run your app and see the output of the app. 

Output:

FinalOutput




Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg