Chart Layout & Legends

Layout charts with plots and legends

Laying out Charts

ChartLayout is a simple aid for laying out the plot, a title, and a legend. The plot is the main content, with an optional legend that can be placed above, below, to the left, or to the right of it. A title is centered above the other content. ChartLayout has few options and expects the contained Composables to use padding and borders as preferred to achieve the desired look.

The below example illustrates how the components are placed relative to each other when the legend is placed to the left of the plot.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
    val itemCount = 5
    val palette = generateHueColorPalette(itemCount)
    ChartLayout(
        modifier = Modifier.border(0.dp, Color.Green).padding(16.dp),
        title = { Text("Chart Title", style = MaterialTheme.typography.titleLarge) },
        legend = {
            ColumnLegend(
                modifier = Modifier.padding(16.dp).border(1.dp, Color.Black).padding(16.dp),
                itemCount = itemCount,
                symbol = { Symbol(shape = RectangleShape, fillBrush = SolidColor(palette[it])) },
                label = { Text("Item $it") }
            )
        },
        legendLocation = LegendLocation.LEFT
    ) {
        Box(modifier = Modifier.fillMaxSize().border(1.dp, Color.Blue), contentAlignment = Alignment.Center) {
            Text("Graph Area")
        }
    }
/examples/src/jvmMain/kotlin/io/github/koalaplot/example/ChartLayout1.kt

Chart layout

Legends

To assist with generating legends, Koala Plot provides two Composables ColumnLegend and FlowLegend. The above example included an example of ColumnLegend. It places a symbol, a label, and a value in rows, each aligned in columns. A ColumnLegend with all three items in each row is included in the example below:

1
2
3
4
5
6
7
    ColumnLegend(
        modifier = Modifier.padding(16.dp).border(1.dp, Color.Black).padding(16.dp),
        itemCount = itemCount,
        symbol = { Symbol(shape = RectangleShape, fillBrush = SolidColor(palette[it])) },
        label = { Text("Item $it") },
        value = { Text("${it * 10}%") }
    )
/examples/src/jvmMain/kotlin/io/github/koalaplot/example/ColumnLegend1.kt

Column Legend

FlowLegend is best used above or below the graph, and will expand to be as wide as necessary to fit its content. Once it reaches the maximum width allocated to it, it will place additional items on the next row. The below example demonstrates this wrapping feature when the available width is too small to hold all items in a single row:

1
2
3
4
5
6
    FlowLegend(
        modifier = Modifier.padding(16.dp).border(1.dp, Color.Black).padding(16.dp),
        itemCount = itemCount,
        symbol = { Symbol(shape = RectangleShape, fillBrush = SolidColor(palette[it])) },
        label = { Text("Item $it") },
    )
/examples/src/jvmMain/kotlin/io/github/koalaplot/example/FlowLegend1.kt

Flow Legend