MPAndroidChart: horizontal bar chart with gaps

Viewed 549

I'm using MPAndroidChart with Kotlin in Android Studio. I manage to build the standard charts from the examples, but I need something different.

Is it possible to build a horizontal bar chart where the bars contain gaps? Something similar to this: horizontal bar chart with gaps

What I want to achieve is display the occurences of specific events (e.g. Event 1, Event 2, Event 3, and Event 4) on a timeline (e.g. from 0 hours to 24 hours -> an entire day) using bars.

So in the image above, roughly estimated: event 1 occurs from 0H > 1H, then again from 6H > 10H, and similar for the other events.

Can I do this with MPAndroidChart?

1 Answers

Here's what I managed to do based on what I had said:

val events = listOf(
        Event(0, 0f, 1.5f),
        Event(2, 1.5f, 1.5f),
        Event(1, 3f, 3f),
        Event(3, 6f, 1f),
        Event(0, 7f, 3f),
        Event(1, 10f, 1f),
        Event(2, 11f, 7f),
        Event(3, 18f, 8f))

val categoryColors = listOf(
        Color.parseColor("#ff3f1f"),
        Color.parseColor("#9fff3f"),
        Color.parseColor("#ffff3f"),
        Color.parseColor("#1fbf3f"))

val bgColor = requireContext().obtainStyledAttributes(
        intArrayOf(android.R.attr.windowBackground)).use {
    it.getColor(0, 0)
}

val chart = binding.barChart
val dataSets = mutableListOf<IBarDataSet>()
val vals = events.mapIndexed { i, event ->
    event.duration
}.toFloatArray()
for (i in 0 until 4) {
    val colors = events.mapIndexed { j, event ->
        if (event.category == i) categoryColors[i] else bgColor
    }.toIntArray()
    dataSets += BarDataSet(listOf(BarEntry(i.toFloat(), vals, null)), i.toString()).apply {
        stackLabels = arrayOfNulls(1)
        setColors(*colors)
        isHighlightEnabled = false
        setDrawValues(false)
    }
}
chart.apply {
    data = BarData(dataSets)
    description = null
    axisRight.apply {
        setDrawGridLines(false)
    }
    axisLeft.apply {
        setDrawLabels(false)
        setDrawGridLines(false)
    }
    xAxis.apply {
        setDrawLabels(false)
        setDrawGridLines(false)
    }
    legend.isEnabled = false
}

And the Event class:

data class Event(val category: Int,
                 val time: Float,
                 val duration: Float)

The result: result

Related