Pie & Donut Charts

Pie and donut charts are essentially the same, except the donut chart has a hole in the middle and with Koala Plot you can put a Composable in that space.

The pie and donut chart take as their data a List<Float>. Pie slices start at 12 O’Clock and go clockwise around the circult, starting at the first element of the list. Below is a simple example with 10 random values:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    val random = Random(10)

    val data: List<Float> = buildList {
        for (i in 1..10) {
            add(random.nextFloat() * 10f)
        }
    }

    PieChart(
        data,
        label = { i ->
            Text(data[i].toString())
        }
    )
/examples/src/jvmMain/kotlin/io/github/koalaplot/example/Pie1.kt

Pie chart

Each slice is scaled to be proportional to the total of all values.

There are many options for tailoring the visual appearance of the Pie Chart and a good way to quickly see their effect is by looking at the Pie Chart from the web samples.

By default, the pie chart will place slice labels around the outer perimeter of the pie in a circle, given sufficient space for the labels. If there isn’t sufficient space, it will push the labels up or down so that they don’t overlap each other. If you don’t like this approach, the position of the labels is pluggable and can be customized by implementing the LabelPositionProvider interface and passing your implementation to PieChart().

Donut Charts

The donut chart is the same in all ways as the pie chart except you can specify a “hole” size as a fraction of the overall pie diameter, and you can provide a Composable to display within the empty space. This is demonstrated below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    val random = Random(10)

    val data: List<Float> = buildList {
        for (i in 1..10) {
            add(random.nextFloat() * 10f)
        }
    }

    PieChart(
        data,
        label = { i ->
            Text(data[i].toString())
        },
        holeSize = 0.75F,
        holeContent = {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center,
            ) {
                Column {
                    Text("Total", style = MaterialTheme.typography.titleLarge)
                    Text(
                        ((data.sum() * 100F).roundToInt() / 100F).toString(),
                        style = MaterialTheme.typography.displaySmall
                    )
                }
            }
        }
    )
/examples/src/jvmMain/kotlin/io/github/koalaplot/example/Pie2.kt

Donut chart


Last modified April 23, 2024: Changes for 0.6.0 (19018a1)