Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 741
Drunken Daddy Avatar asked Apr 27 '15 06:04

Drunken Daddy


People also ask

How do you add color to a bar graph?

On a chart, select the individual data marker that you want to change. On the Format tab, in the Shape Styles group, click Shape Fill. Do one of the following: To use a different fill color, under Theme Colors or Standard Colors, click the color that you want to use.

How do I change the color of my bar graph in SAS?

If you have SAS 9.3 or later, you can do this using the SGPLOT procedure. Use LIMITATTRS to change the color of the error bars. You can change the color of the bars themselves using FILLATTRS.


2 Answers

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); 
like image 167
m4n3k4s Avatar answered Sep 24 '22 03:09

m4n3k4s


You can find out the documentation about setting colors in MPAndroidChart from this link

    LineDataSet setComp1 = new LineDataSet(valsComp1, "Company 1");   // sets colors for the dataset, resolution of the resource name to a "real" color is done internally   setComp1.setColors(new int[] { R.color.red1, R.color.red2, R.color.red3, R.color.red4 }, Context);    LineDataSet setComp2 = new LineDataSet(valsComp2, "Company 2");   setComp2.setColors(new int[] { R.color.green1, R.color.green2, R.color.green3, R.color.green4 }, Context); 
like image 20
Alex Chengalan Avatar answered Sep 22 '22 03:09

Alex Chengalan