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.
Regards.
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With