Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
910 views
in Technique[技术] by (71.8m points)

android - MPAndroidChart, set different color to bar in a bar chart based on y axis values

I'm plotting a bar chart using MPAndroid chart. Now all my bars have the same color but I want different colors for the bars based on Y axis values, like if value >100. color = red, like in the picture below. Is that possible? someone please help me.

enter image description here

Regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can override the BarDataSet class to achieve this

public class MyBarDataSet extends BarDataSet {


    public MyBarDataSet(List<BarEntry> yVals, String label) {
        super(yVals, label);
    }

    @Override
    public int getColor(int index) {
        if(getEntryForXIndex(index).getVal() < 95) // less than 95 green
            return mColors.get(0);
        else if(getEntryForXIndex(index).getVal() < 100) // less than 100 orange
            return mColors.get(1);
        else // greater or equal than 100 red
            return mColors.get(2);
    }

}

And you need to define your colors like this:

MyBarDataSet set = new MyBarDataSet(yVals, "");
set.setColors(new int[]{ContextCompat.getColor(context, R.color.green), 
                ContextCompat.getColor(context, R.color.orange), 
                ContextCompat.getColor(context, R.color.red)});
ArrayList<BarDataSet> dataSets = new ArrayList<>();
dataSets.add(set);


BarData data = new BarData(xVals, dataSets);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...