MPAndroidChart - 使 xaxis 间距相对

MPAndroidChart - make xaxis spacing relative

我有一个 MPAndroidChart 折线图,它在 x 轴上显示日期,在 ya 轴上显示权重。事实上,沿 x 轴的数据点都是均匀分布的,但我想让它们相对于每个权重条目之间的时间段。尽我所能,我在 MPAndroidChart 文档中找不到任何描述如何执行此操作的内容,或者它是否受支持。谁能在这里为我指出正确的方向?

下面是创建图表的代码(结果是均匀间距):

private fun loadChart(weightList: List<FormattedWeight>) {
    if (weightList.isEmpty()) { return }
        
    val weights = ArrayList<Entry>()
    val dates = ArrayList<Date>()


    for (i in weightList.indices) {
        val weight = weightList[i]
        weights.add(Entry(i.toFloat(), weight.Weight!!.toFloat()))
        dates.add(weight.WeightDate!!)
    }
    val dataSet = LineDataSet(weights, "Weights")
    dataSet.mode = LineDataSet.Mode.LINEAR

    val xaxis = binding.weightChart.xAxis

    xaxis.granularity=2f
    dataSet.color = Color.BLUE
    dataSet.setCircleColor(Color.BLUE)
    xaxis.position = XAxis.XAxisPosition.BOTTOM

    xaxis.valueFormatter = object : ValueFormatter() {
        private val mFormat = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT)
        override fun getFormattedValue(value: Float): String {
            return try {
                mFormat.format(dates[value.toInt()])
            } catch (e: Exception) {
                ""
            }
        }
    }

    binding.weightChart.data = LineData(dataSet)
    binding.weightChart.description.isEnabled = false
    binding.weightChart.legend.isEnabled = false
    binding.weightChart.invalidate()
    binding.weightChart.moveViewToX(weights[weights.size - 1].y)

}

均匀间距

相对间距

我想通了x轴间距设置在

Entry(float x, float y)

如果将 x 参数设置为均匀递增的数字(例如:1、2、3...),您将获得均匀分布的数据点。但是,如果您将它们设置为不同的增量(例如:1、1.3、2.2...),您将获得相对间距。所以这是我用来实现这个的代码:

    val spacing = calcRelativeSpacing(weightList)
    
    for (i in weightList.indices) {
        val weight = weightList[i]
        weights.add(Entry(spacing[i], weight.Weight!!.toFloat()))
        dates.add(weight.WeightDate!!)
    }

注意对 calcRelativeSpacing(weightList) 的调用:

private fun calcRelativeSpacing(entries: List<FormattedWeight>): ArrayList<Float> {
    val startDate = Instant(entries.get(0).WeightDate)
    val endDate = Instant(entries.get(entries.lastIndex).WeightDate)
    val days = Days.daysBetween(startDate, endDate).days
    val dayInterval = (days / entries.size).toFloat()
    val spacing = ArrayList<Float>()
    spacing.add(1f)
    for (i in 1 until entries.size) {
        spacing.add(spacing[i-1] + (Days.daysBetween(Instant(entries.get(i-1).WeightDate), Instant(entries.get(i).WeightDate)).days / dayInterval))
    }
    return spacing
}

结果: