Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 104 ยท Building a Real UI

Charts and Graphs on Android

Draw pie, bar and line charts in Jetpack Compose with Canvas, scale data to pixels, choose a chart library such as Vico, and make charts accessible with text summaries.

A budget app needs a pie chart of spending, a fitness app needs a line of weekly steps, a shop dashboard needs bars for sales. Android has no chart widget in the framework or in Material 3, so you have two choices: draw the chart yourself with Canvas, or add a charting library. For simple charts, drawing is less work than it sounds, because a chart is just data scaled to pixels. For zoomable, interactive, multi-axis charts a library saves weeks.

This lesson teaches the drawing approach step by step, shows the scaling maths that every chart shares, gives an honest overview of the libraries, and covers accessibility, which charts often forget. Android UI cannot run here, so the real Compose code is read-only; the TryIts are plain Kotlin stand-ins that run the same maths (axis scaling, pie angles, point mapping) and print the result as text.

A chart is a mapping

Every chart does the same three things:

  1. Find the data range: the smallest and largest value.
  2. Map each value into the drawing area (a value becomes a pixel position).
  3. Draw shapes at those positions: rectangles for bars, arcs for pie slices, a path through points for a line.

The mapping is linear interpolation. For a value v between min and max, drawn into a height h where y grows downward, the y pixel is h - (v - min) / (max - min) * h. The "y grows downward" part is the most common source of upside-down charts.

Bars should start at zero, otherwise a bar twice as tall does not mean twice the value and the chart misleads. Lines may use a tighter range, but tell the reader the axis does not start at zero.

The first stand-in does the scaling for a bar chart, including "nice" axis ticks (round numbers like 0, 50, 100) and a text rendering of the bars.

Kotlin Bar chart scaling and nice ticks (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Drawing with Canvas

In Compose, Canvas(modifier) { ... } gives you a DrawScope. Inside it, size is the area in pixels, and functions like drawRect, drawArc, drawLine, drawPath and drawCircle paint on it. Pixels depend on density, so convert dp to pixels with dp.toPx() inside the scope. Colors should come from the theme (see Material 3 theming) so the chart works in dark mode.

Kotlin
// read-only example: a bar chart
@Composable
fun BarChart(values: List<Float>, labels: List<String>, modifier: Modifier = Modifier) {
    val barColor = MaterialTheme.colorScheme.primary
    val maxValue = (values.maxOrNull() ?: 1f).coerceAtLeast(1f)

    Canvas(modifier.fillMaxWidth().height(200.dp)) {
        val slot = size.width / values.size
        val barWidth = slot * 0.6f
        values.forEachIndexed { i, v ->
            val barHeight = v / maxValue * size.height
            drawRoundRect(
                color = barColor,
                topLeft = Offset(i * slot + (slot - barWidth) / 2, size.height - barHeight),
                size = Size(barWidth, barHeight),
                cornerRadius = CornerRadius(8.dp.toPx()),
            )
        }
    }
}

Canvas draws only shapes. Text labels are easier as ordinary composables placed in a Row under the canvas, or drawn with rememberTextMeasurer() and drawText when they must sit at exact pixel positions. Because Canvas re-draws whenever state it reads changes, animate a chart by animating a value (animateFloatAsState) and multiplying the bar heights by it (see animation). Keep heavy computation out of the draw block: compute scaled values with remember(values) { ... } or in the ViewModel, as in recomposition.

Pie charts

A pie chart splits 360 degrees in proportion to the values. drawArc takes a start angle and a sweep angle, in degrees, where 0 degrees is the 3 o'clock position and angles grow clockwise. To start at the top (12 o'clock), begin at -90.

Kotlin
// read-only example: a donut chart
@Composable
fun DonutChart(slices: List<Pair<Color, Float>>, modifier: Modifier = Modifier) {
    val total = slices.sumOf { it.second.toDouble() }.toFloat()
    Canvas(modifier.size(160.dp)) {
        val stroke = 28.dp.toPx()
        var start = -90f
        slices.forEach { (color, value) ->
            val sweep = value / total * 360f
            drawArc(
                color = color,
                startAngle = start,
                sweepAngle = sweep - 1f,                    // 1 degree gap between slices
                useCenter = false,                          // false + Stroke = donut
                topLeft = Offset(stroke / 2, stroke / 2),
                size = Size(size.width - stroke, size.height - stroke),
                style = Stroke(width = stroke),
            )
            start += sweep
        }
    }
}

Pie charts work for a few parts of one whole (up to about five). More slices, or values that are close, are better as a bar chart. The percentages you print must add up to 100, which plain rounding does not guarantee (33.3 + 33.3 + 33.3 = 99.9, and 3 rounded values can give 99 or 101). The second stand-in computes slice angles and uses the largest remainder method so the labels always total exactly 100.

Kotlin Pie angles and percentages that add up (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Line charts

A line chart maps each data point to an Offset and connects them with a Path. The x position is usually the index divided by the number of gaps; the y position uses the interpolation formula above.

Kotlin
// read-only example: a line with a gradient area is a short extension of this
@Composable
fun LineChart(points: List<Float>, modifier: Modifier = Modifier) {
    val lineColor = MaterialTheme.colorScheme.primary
    val minV = points.min()
    val maxV = points.max()
    val range = (maxV - minV).takeIf { it > 0f } ?: 1f

    Canvas(modifier.fillMaxWidth().height(180.dp)) {
        val stepX = size.width / (points.size - 1).coerceAtLeast(1)
        val offsets = points.mapIndexed { i, v ->
            Offset(i * stepX, size.height - (v - minV) / range * size.height)
        }
        val path = Path().apply {
            offsets.forEachIndexed { i, p -> if (i == 0) moveTo(p.x, p.y) else lineTo(p.x, p.y) }
        }
        drawPath(path, lineColor, style = Stroke(width = 3.dp.toPx(), cap = StrokeCap.Round))
        offsets.forEach { drawCircle(lineColor, radius = 4.dp.toPx(), center = it) }
    }
}

For smooth curves use cubicTo with control points halfway between neighbors, and for a filled area close the path down to the baseline and fill it with drawPath plus a Brush.verticalGradient. For touch support (show the value of the nearest point), add Modifier.pointerInput and find the point whose x is closest to the finger; the gesture tools are in gestures and input events.

Libraries

Writing your own is right for a handful of simple charts. A library is right when you need many chart types, zooming, several axes, tooltips or large data sets. The list changes quickly, so check each project's activity and license before you commit:

  • Vico is a Compose-first chart library with line, column and candlestick charts, scrolling, zooming and markers. It is a good default for a new Compose app.
  • MPAndroidChart is the long-standing View-based library with a huge feature list (line, bar, pie, radar, scatter, combined). You use it from Compose through AndroidView (see Views interop). Its development has been slow for years, so weigh that.
  • YCharts and several other Compose-native libraries offer ready-made pie, bar and line charts with less setup.
  • WebView with a JavaScript chart library works but adds weight and a bridge to secure; see WebView and search.

All of these are third-party dependencies you add in Gradle (see Gradle build); the snippets in their documentation are not runnable here, so treat library API names as something to check against the current version.

Accessibility and honesty

A canvas is invisible to TalkBack. A chart with no text alternative gives blind users nothing, and even sighted users benefit from the numbers.

  • Add Modifier.semantics { contentDescription = "Weekly sales. Highest on Thursday with 88 units." } to the chart, written as a short summary of the finding, not a list of pixels.
  • Offer the data in a table or list nearby for users who want exact values.
  • Do not rely on color alone: use labels, patterns or direct value text, and check contrast in dark mode (see accessibility and localization).
  • Start bars at zero, keep scales consistent between charts users compare, and label units.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In a Compose Canvas, how do you convert a value v (between min and max) into a y pixel for a chart of height h?

    Interpolate into the range and subtract from the height, because y grows downward on a canvas. Without the subtraction the chart is upside down.
  2. 2. Where does angle 0 point in drawArc, and which way do angles grow?

    0 degrees is at 3 o'clock and angles grow clockwise. Start at -90 to begin at the top.
  3. 3. Why should bar charts start at zero?

    If the baseline is above zero, a bar that looks twice as tall may be only slightly larger in value.
  4. 4. What is the best way to make a Canvas chart usable with TalkBack?

    Drawn shapes have no accessibility information. Provide a spoken summary and an alternative text or table view of the data.

Summary

  • A chart maps data ranges to pixels; remember that y grows downward and bars start at zero.
  • Canvas with drawRoundRect, drawArc (0 degrees = 3 o'clock, clockwise) and drawPath covers bar, pie/donut and line charts.
  • Compute scaled values outside the draw block, animate with a state value, and take colors from the theme.
  • Use the largest remainder method so pie percentages total 100.
  • Vico, MPAndroidChart and YCharts are options when you need more than basic charts; verify them against their current docs.
  • Give charts a text summary and a data table so they are accessible.

Next: Gestures and Input Events