Add coloured regions with MPAndroidChart

Viewed 44

I have been trying to add a coloured region to my chart. I found this solution but I am finding problems to draw grid lines in the front as you can see in this image. Chart example

I have avoided xAxis grid lines by checkig for values but it's not a clean solution... I have seen old questions about this topic but maybe someone has an updated solution

1 Answers

This solution will add a vertical background from the top of the chart to the bottom at the first 10 X-Axis units. You can tweak it for your needs

add this class

class BgRenderer(
    chart: LineChart,
    private val paint: Paint,
) :
XAxisRenderer(
    chart.viewPortHandler,
    chart.xAxis,
    chart.getTransformer(YAxis.AxisDependency.LEFT)
) {

override fun renderAxisLine(c: Canvas) {
    super.renderAxisLine(c)

    val bgRect =FloatArray(4)

    bgRect[0] =0f
    bgRect[2] =10f
    transformer.pointValuesToPixel(bgRect)

    c.drawRect(
        bgRect[0],
        mViewPortHandler.contentTop(),
        bgRect[2],
        mViewPortHandler.contentBottom(),
        paint
    )
}
}

consume the class in your activity

myChart.setXAxisRenderer(
        BgRenderer(
            myChart,
            myPaint,
        )
    )

myChart.invalidate()
Related