androidkotlinmpandroidchart

MPAndroidChart : How to have colors filled between LimitLines in LineChart


I am trying to fill color between limit lines and have legend just like below - required screenshot I tried using example given here - https://github.com/PhilJay/MPAndroidChart/issues/485 But unable to achieve. Last I can do about legends is to have my own textviews. But color in between is still an issue.


Solution

  • You can make a chart like that by creating a LineDataSet for each section and setting a fill color and a fill formatter with a lower y value.

    To get this chart:

    demo chart You would use

    val ds1 = LineDataSet(listOf(Entry(0f,1f), Entry(10f,1f)), "Low").apply {
        setDrawFilled(true)
        fillAlpha = 128
        fillColor = Color.YELLOW
        color = Color.YELLOW
        fillFormatter = IFillFormatter { _, _ -> 0f } // fill down to y = 0
        setDrawCircles(false)
        lineWidth = 0f
        setDrawValues(false)
        disableDashedHighlightLine()
        isHighlightEnabled = false
    }
    
    val ds2 = LineDataSet(listOf(Entry(0f,3f), Entry(10f,3f)), "Mid").apply {
        setDrawFilled(true)
        fillAlpha = 128
        fillColor = Color.GREEN
        color = Color.GREEN
        fillFormatter = IFillFormatter { _, _ -> 1f } // fill down to y = 1
        setDrawCircles(false)
        lineWidth = 0f
        setDrawValues(false)
        disableDashedHighlightLine()
        isHighlightEnabled = false
    }
    
    val ds3 = LineDataSet(listOf(Entry(0f,7f), Entry(10f,7f)), "High").apply {
        setDrawFilled(true)
        fillAlpha = 128
        fillColor = Color.RED
        color = Color.RED
        fillFormatter = IFillFormatter { _, _ -> 3f } // fill down to y = 3
        setDrawCircles(false)
        lineWidth = 0f
        setDrawValues(false)
        disableDashedHighlightLine()
        isHighlightEnabled = false
    }
    
    val dsLine = LineDataSet(listOf(Entry(1f,2f), Entry(4f,5f), Entry(6f,4f)), "Points").apply {
        color = Color.BLACK
        setCircleColor(Color.BLACK)
        lineWidth = 2f
        setDrawValues(false)
        circleHoleColor = Color.BLACK
        circleRadius = 3f
    }
    
    chart.axisLeft.axisMinimum = 0f
    chart.axisLeft.axisMaximum = 6f
    chart.xAxis.position = XAxis.XAxisPosition.BOTTOM
    chart.axisRight.isEnabled = false
    
    chart.data = LineData(listOf(ds1, ds2, ds3, dsLine))
    chart.description.text = ""
    

    Note that this solution only works for filling to horizontal lines. If you want to fill to non-horizontal lines you will need a more complicated solution like this one