Charts in Jetpack compose - Create Bar Chart with Jetpack compose

Last updated Feb 11, 2022

In this jetpack compose tutorial example, we will see how to create Bar Chart using Jetpack Compose. Jetpack Compose is a cutting-edge toolkit for creating native Android user interfaces.It simplifies and accelerates UI development on Android by using minimal code, powerful tools, and explicit Kotlin APIs. Compose supports material design ideas. Many of its UI elements are built with material design in mind right out of the box.

A bar chart, also known as a bar graph, is a type of chart or graph that uses rectangular bars with heights or lengths proportional to the values they represent to display categorical data.

Implementation

Step 1. Create a new Project in Android Studio.

File > New > New Project > Select (Empty Compose Activity) > Next > Enter Name (BarChartJetpack) > FINISH.

After creating the new project, Android Studio starts Gradle and builds your project, which may take a few seconds.


Step 2.  At first, Open MainActivity.kt file

First we will create a composable function of BarChart() in which we use Canvas for display bar chart where we define point list, animate the graph, draw lines, rectangle and so on..

@Composable
fun BarChart() {
    val point = listOf(
        Point(10, 200),
        Point(90, 100),
        Point(170, 40),
        Point(250, 200),
        Point(330, 120),
        Point(410, 100),
        Point(490, 200),
    )

    val context = LocalContext.current
    var start by remember { mutableStateOf(false) }
    val heightPre by animateFloatAsState(
        targetValue = if (start) 1f else 0f,
        animationSpec = FloatTweenSpec(duration = 1000)
    )

    Canvas(
        modifier = Modifier
            .fillMaxWidth()
            .height(400.dp)
            .background(Color.Yellow).padding(40.dp)
            .pointerInput(Unit) {
                detectTapGestures(
                    onTap = {
                        val i = identifyCLickItem(point, it.x, it.y)
                        Toast
                            .makeText(context, "onTap: $i", Toast.LENGTH_SHORT)
                            .show()
                    }
                )
            }
    ) {
        drawLine(
            start = Offset(10f, 600f),
            end = Offset(10f, 0f),
            color = Color.Black,
            strokeWidth = 2f
        )
        drawLine(
            start = Offset(10f, 600f),
            end = Offset(600f, 600f),
            color = Color.Black,
            strokeWidth = 1f
        )
        start = true

        for (p in point) {
            drawRect(
                color = Color.DarkGray,
                topLeft = Offset(p.x + 30f, 600 - (600 - p.y) * heightPre),
                size = Size(55f, (600 - p.y) * heightPre)
            )
        }
    }
}


Now we will create a private function identifyClickItem() which will help to get position by clicking on chart whether its a no.(1,2,3...) or -1.

private fun getPositionFromAngle(
    angles: List,
    touchAngle: Double
): Int {
    var totalAngle = 0f
    for ((i, angle) in angles.withIndex()) {
        totalAngle += angle
        if (touchAngle <= totalAngle) {
            return i
        }
    }
    return -1
}


Finally we will call our BarChart() function inside onCreate() function, we will use scaffold and TopAppBar for display the title in action bar.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            BarChartJetpackTheme {
                Surface(color = MaterialTheme.colors.background) {
                    Scaffold(
                        topBar = {
                            TopAppBar(
                                title = {
                                    Text(
                                        text = "Bar Chart",
                                        modifier = Modifier.fillMaxWidth(),
                                        textAlign = TextAlign.Center
                                    )
                                }
                            )
                        }
                    ) {
                        Column(
                            modifier = Modifier.fillMaxSize(),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {
                            BarChart()
                        }
                    }
                }
            }
        }
    }
}

 

Complete example code create Bar chart using Jetpack Compose

import android.graphics.Point
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.FloatTweenSpec
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.nishajain.barchartjetpack.ui.theme.BarChartJetpackTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            BarChartJetpackTheme {
                Surface(color = MaterialTheme.colors.background) {
                    Scaffold(
                        topBar = {
                            TopAppBar(
                                title = {
                                    Text(
                                        text = "Bar Chart",
                                        modifier = Modifier.fillMaxWidth(),
                                        textAlign = TextAlign.Center
                                    )
                                }
                            )
                        }
                    ) {
                        Column(
                            modifier = Modifier.fillMaxSize(),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {
                            BarChart()
                        }
                    }
                }
            }
        }
    }
}

private fun identifyCLickItem(
    points: List,
    x: Float,
    y: Float
): Int {
    for ((index, point) in points.withIndex()) {
        if (x > point.x + 20 && x < point.x + 20 + 40) {
            return index
        }
    }
    return -1
}

@Composable
fun BarChart() {
    val point = listOf(
        Point(10, 200),
        Point(90, 100),
        Point(170, 40),
        Point(250, 200),
        Point(330, 120),
        Point(410, 100),
        Point(490, 200),
    )

    val context = LocalContext.current
    var start by remember { mutableStateOf(false) }
    val heightPre by animateFloatAsState(
        targetValue = if (start) 1f else 0f,
        animationSpec = FloatTweenSpec(duration = 1000)
    )

    Canvas(
        modifier = Modifier
            .fillMaxWidth()
            .height(400.dp)
            .background(Color.Yellow).padding(40.dp)
            .pointerInput(Unit) {
                detectTapGestures(
                    onTap = {
                        val i = identifyCLickItem(point, it.x, it.y)
                        Toast
                            .makeText(context, "onTap: $i", Toast.LENGTH_SHORT)
                            .show()
                    }
                )
            }
    ) {
        drawLine(
            start = Offset(10f, 600f),
            end = Offset(10f, 0f),
            color = Color.Black,
            strokeWidth = 2f
        )
        drawLine(
            start = Offset(10f, 600f),
            end = Offset(600f, 600f),
            color = Color.Black,
            strokeWidth = 1f
        )
        start = true

        for (p in point) {
            drawRect(
                color = Color.DarkGray,
                topLeft = Offset(p.x + 30f, 600 - (600 - p.y) * heightPre),
                size = Size(55f, (600 - p.y) * heightPre)
            )
        }
    }
}

 

Step 3. Add the following colors to your Color.kt file

import androidx.compose.ui.graphics.Color

val Purple200 = Color(0xFFBB86FC)
val Purple500 = Color(0xFFFFC107)
val Purple700 = Color(0xFFFFEB3B)
val Teal200 = Color(0xFF03DAC5)

 


Step 4. Run the app in your emulator or real device and you will get the following output:

OUTPUT

Bar Chart Using Jetpack Compose

 

Tap on Bar 

 

Bar Chart Using Jetpack Compose 2


Conclusion: In this article we have covered how to create Bar Chart using JetPack Compose.

Jetpack compose Chart Examples

Create Pie Chart with Jetpack compose

Create Line Chart with Jetpack compose

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1502 Views