问题描述
我在Android Studio中将MPAndroidChart与Kotlin结合使用.我设法从示例中构建了标准图表,但是我需要一些不同的东西.
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
我想要实现的是使用时间条在时间轴(例如,从0小时到24小时->一整天)上显示特定事件(例如事件1,事件2,事件3和事件4)的发生情况.
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.
因此,在上图中,可以粗略估计:事件1从0H> 1H发生,然后再次从6H> 10H发生,其他事件类似.
So in the image above, roughly estimated: event 1 occurs from 0H > 1H, then again from 6H > 10H, and similar for the other events.
我可以使用MPAndroidChart做到这一点吗?
Can I do this with MPAndroidChart?
推荐答案
这是我根据我所说的做的事情:
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
}
和 Event
类:
data class Event(val category: Int,
val time: Float,
val duration: Float)
结果:
这篇关于MPAndroidChart:带有间隙的水平条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!