Thursday 3 December 2020

How to change line and fill color of MPAndroidChart line chart based on if y axis value is positive or negative

Was wondering if it is possible to change the line and fill color for the line chart based on if the y-axis values are positive or negative. An example of it is below

enter image description here

Below is what i could achieve with the following code

enter image description here

    private fun setUpLineChart() {
        val lineData = getDataSet()
        view.lineChart.apply {
            data = lineData
            description.isEnabled = false
            setScaleEnabled(false)
            setTouchEnabled(false)
            legend.isEnabled = false
            axisLeft.apply {
                setDrawLabels(false)
                setDrawGridLines(false)
                setDrawAxisLine(false)
                spaceBottom = 30f
            }
            axisRight.apply {
                setDrawLabels(false)
                setDrawGridLines(false)
                setDrawAxisLine(false)
            }
            xAxis.apply {
                setDrawLabels(false)
                setDrawGridLines(false)
                setDrawAxisLine(false)
            }
            animateXY(700, 1000, Easing.EaseInOutQuad)
        }
    }

    private fun getDataSet(): LineData {
        val entries = mutableListOf<Entry>()
        val dataList = listOf(1, 20, -20, 33, 54, 7, -18, 2)

        dataList.forEachIndexed { index, element ->
            entries.add(Entry(index.toFloat(), element.toFloat()))
        }

        val dataSet = LineDataSet(entries, "")
        dataSet.apply {
            setDrawCircles(false)
            valueTextSize = 0f
            lineWidth = 3f
            mode = LineDataSet.Mode.HORIZONTAL_BEZIER
            color = ContextCompat.getColor(view.context, R.color.colorOnSurface)
            setDrawFilled(true)
            fillColor = ContextCompat.getColor(view.context, R.color.colorSurface2)
        }
        return LineData(dataSet)
    }


from How to change line and fill color of MPAndroidChart line chart based on if y axis value is positive or negative

No comments:

Post a Comment