Skip to content Skip to sidebar Skip to footer

Mpandroidchart: Horizontal Bar Chart With Gaps

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 horizonta

Solution 1:

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 in0 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:

dataclassEvent(val category: Int,
                 val time: Float,
                 val duration: Float)

The result: result

Post a Comment for "Mpandroidchart: Horizontal Bar Chart With Gaps"