How to set color for values in MPAndroidChart?

一个人想着一个人 提交于 2021-01-29 02:46:52

问题


I am using MPAndroidChart.

Searched through the documentation but couldn't find anything that implemented correctly. I have a graph at the moment but I want to change the color of the line if it goes over a certain amount. Graph Example In the example I have linked, it shows a line drawn through the values from 10. I would like this line (the one going through the chart) and the color of the line in the chart to change color over 10. Is this possible? Using MPAndroidChart. I have one dataset at the moment.

Thanks in advance.


回答1:


Yes. You just need a simple logic.

List<Integer> colors = ...;
List<Entry> entries = ...;

for(...) {

   entries.add(...);

   if(entries.get(i).getVal() > 10) 
       colors.add(customcolor);
   else 
       colos.add(othercolor);
}



回答2:


With LineDataSet.setColors() you can add a list of colors. Each color entry is for one data entry. ' The trick is to calculate intermediate values for crossing the border.

Everytime I add a data entry, i call this method

private fun addDiffValue(newEntry : Entry){
    val last = recordedValues[2].last()
    val limit = 50f
    if(last.y < limit && newEntry.y > limit  ){
        val gradient = (newEntry.y - last.y) / (newEntry.x - last.x)
        val x_border = last.x + ((limit - last.y) / gradient)
        recordedValues[2].add(Entry(x_border, limit))
        diffColors.add(Color.LTGRAY)
        diffColors.add(Color.RED)
    }
    // Vorher größer, jetzt kleiner
    else if(last.y > limit && newEntry.y < limit) {
        val gradient = (newEntry.y - last.y) / (newEntry.x - last.x)
        val x_border = last.x + ((limit - last.y) / gradient)
        recordedValues[2].add(Entry(x_border, limit))
        diffColors.add(Color.RED)
        diffColors.add(Color.LTGRAY)
    }else if(last.y > limit ){
        diffColors.add(Color.RED)
    } else {
        diffColors.add(Color.LTGRAY)
    }
    recordedValues[2].add(newEntry)
}

It is important to say, that I start with recordedValues[2].add(Entry(0f,0f)), otherwise last() would throw an error.

I create the LineDataSet and add the colors:

val dataSet3 = LineDataSet(recordedValues[2], "My Label")
dataSet3.setColors(diffColors)

As you can see in this screenshot, all values above 50 are red.



来源:https://stackoverflow.com/questions/35707532/how-to-set-color-for-values-in-mpandroidchart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!