0

I'm using a BarChart in an app but sometimes when I re-draw it the bars width is not respected and I get inconsistent results (even though the amount of values in the X axis is always 100).

This is how I want it to look always:

enter image description here

but sometimes it looks like this:

enter image description here

enter image description here

Does anyone know why this happens and how can I force it to always look the same?

I think it has something to do with the range of values in the X axis, as the chart looks good when the range goes from 0 to 50 or similar, but it looks bad when the range is smaller.

I'm already setting a bar width value like this but it doesn't help:

barChartView?.data?.barWidth = 0.3f

This is the full chart configuration I'm using (this method runs only once when the Fragment is created):

private fun setUpChartView() {
    barChartView?.setTouchEnabled(false)

    val xAxis = barChartView?.xAxis
    val yAxis = barChartView?.axisLeft

    // Hide all parts of the chart that we don't want to show
    barChartView?.legend?.isEnabled = false
    barChartView?.description?.isEnabled = false
    barChartView?.setDrawGridBackground(false)
    xAxis?.setDrawGridLines(false)
    xAxis?.setDrawAxisLine(false)
    yAxis?.setDrawAxisLine(false)
    barChartView?.axisRight?.isEnabled = false

    // Show the Y axis grid lines as dashed
    yAxis?.enableGridDashedLine(5f, 10f, 0f)

    val barChartTextColor = getColor(R.color.chart_text)
    val barChartTextSize = 12f
    val barChartLabelsTypeface = Typeface.SANS_SERIF

    // Show the X axis labels at the bottom and set the proper style
    xAxis?.position = XAxis.XAxisPosition.BOTTOM
    xAxis?.textColor = barChartTextColor
    xAxis?.textSize = barChartTextSize
    xAxis?.typeface = barChartLabelsTypeface

    // Set the proper style for the Y axis labels
    yAxis?.textSize = barChartTextSize
    yAxis?.textColor = barChartTextColor
    yAxis?.typeface = barChartLabelsTypeface

    barChartView?.setNoDataText("")

    val viewPortHandler = barChartView?.viewPortHandler
    val axisTransformer = barChartView?.getTransformer(LEFT)

    // Set a custom axises so that we can control the drawing of the labels and grid lines
    barChartView?.setXAxisRenderer(CustomEntriesXAxisRenderer(viewPortHandler = viewPortHandler,
                                                                 xAxis = xAxis,
                                                                 transformer = axisTransformer))
    barChartView?.rendererLeftYAxis = CustomEntriesYAxisRenderer(viewPortHandler = viewPortHandler,
                                                                    yAxis = yAxis,
                                                                    transformer = axisTransformer)
}

This is the code I use to draw the chart when I get new data:

private fun drawBarChart() {
    // The data list has always 100 items
    val entries = data.map { BarEntry(it.x, it.y) }

    // Prepare the chart data set by adding the entries and configuring its style (colors, etc.)
    val dataSet = BarDataSet(entries, null)
    dataSet.setDrawValues(false)
    dataSet.colors = colorsList

    // Load data to chart
    if (barChartView?.data == null) {
        // If there is no data set yet, create a new data object and add it to the chart (this happens the first
        // time we draw the chart after the Fragment was created, or after an empty data list was returned)
        barChartView?.data = BarData(dataSet)
    } else {
        // If there is already data in the chart, remove the existing data set and add the new one
        barChartView.data?.removeDataSet(0)
        barChartView.data?.addDataSet(dataSet)

        barChartView.notifyDataSetChanged()
    }

    // Set a custom width for the bars or the chart will draw them too wide
    barChartView?.data?.barWidth = 0.3f

    val xAxis = barChartView?.xAxis
    val yAxis = barChartView?.axisLeft

    // Set the min and max values for the Y axis or the chart lib will calculate them and add more values than
    // we need
    yAxis?.axisMinimum = 0f
    yAxis?.axisMaximum = entries.last().y

    // Set the entries that need to be drawn in the X axis, so the chart doesn't calculate them automatically
    (barChartView?.rendererXAxis as CustomEntriesXAxisRenderer).entries = xAxisEntries

    // Set the entries that need to be drawn in the Y axis, so the chart doesn't calculate them automatically
    (barChartView?.rendererLeftYAxis as CustomEntriesYAxisRenderer).entries = yAxisEntries

    // Add the label count to avoid the chart from automatically setting a range of labels instead of the ones we need,
    // which prevents the axis value formatter below to set the correct labels
    xAxis?.setLabelCount(xAxisEntries.size, true)
    yAxis?.setLabelCount(yAxisEntries.size, true)

    // Use a custom value formatter that sets only the needed labels on the axises
    xAxis?.setValueFormatter { value, _ ->
        // TODO
    }
    yAxis?.setValueFormatter { value, _ ->
        // TODO
    }

    // Draw chart
    barChartView?.invalidate()
}

And this is the implementation of the custom axis renderers I created:

class CustomEntriesXAxisRenderer(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, transformer: Transformer?)
    : XAxisRenderer(viewPortHandler, xAxis, transformer) {

    /**
     * Entries used to draw the grid lines and labels on the X axis.
     */
    var entries: List<Float>? = null


    override fun computeSize() {
        entries?.forEachIndexed { i, value ->
            mAxis.mEntries[i] = value
        }

        super.computeSize()
    }

}

class CustomEntriesYAxisRenderer(viewPortHandler: ViewPortHandler?, yAxis: YAxis?, transformer: Transformer?)
    : YAxisRenderer(viewPortHandler, yAxis, transformer) {

    /**
     * Entries used to draw the grid lines and labels on the Y axis.
     */
    var entries: List<Float>? = null


    override fun computeAxisValues(min: Float, max: Float) {
        super.computeAxisValues(min, max)

        entries?.forEachIndexed { i, value ->
            mAxis.mEntries[i] = value
        }
    }

}
Franco
  • 2,711
  • 2
  • 20
  • 27

1 Answers1

0

One of the MPAndroidChart devs said this is indeed a bug in the library and it's now in their to-do list. If anyone is having this issue you can follow the progress here.

In the meantime, after playing around with this for a while I found a (quite ugly) hack that prevents the chart from looking too bad:

barChartView?.data?.barWidth = when (entries.last().x) {
    in 0..30 -> 0.1f
    in 30..60 -> 0.2f
    else -> 0.3f
}

You can adjust the values to what looks good for your data entries, but basically by setting a different bar width depending on the range of X values in the data set you can at least make this a bit better until the bug is fixed.

Franco
  • 2,711
  • 2
  • 20
  • 27