Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the pie slice colors in MPAndroidChart

I need to define specific hex values for each slice in my pie chart.

I'm following the wiki but the method doesn't seem to be working for PieDataSet

PieDataSet dataSet = new PieDataSet(entries, "Fuel");
dataSet.setColors(new int[] { R.color.green1, R.color.green2, R.color.green3, R.color.green4 }, Context);

These errors are shown:

Cannot resolve symbol 'green1'

Expression expected  <-- At the 'Context'

Is there an alternate way to set the pie slice color? This seems to work for Line charts but not for pie.

like image 268
PT_C Avatar asked May 26 '16 18:05

PT_C


People also ask

How do I change the slice colors in an Excel pie chart?

Click the chart you want to change. In the upper-right corner, next to the chart, click Chart Styles. Click Color and pick the color scheme you want, or click Style and pick the option you want.

How to change color of Pie chart in Android Studio?

You can do it from the "colors" window in properties of the chart, click in the first color and you will find the possibility of changing it. You have to select Color by Expression and define a color for each value in your field.


2 Answers

Found a work around:

final int[] MY_COLORS = {Color.rgb(192,0,0), Color.rgb(255,0,0), Color.rgb(255,192,0),Color.rgb(127,127,127), Color.rgb(146,208,80), Color.rgb(0,176,80), Color.rgb(79,129,189)};

ArrayList<Integer> colors = new ArrayList<Integer>();
        
for(int c: MY_COLORS) colors.add(c);
        
dataSet.setColors(colors);
like image 74
PT_C Avatar answered Feb 16 '23 06:02

PT_C


use ContextCompat.getColor(context, R.color.green1) instead of R.color.green1 if not colors will not shown properly.

example code in Kotlin :

 val colorFirst = context?.let { ContextCompat.getColor(it, R.color.colorFirst) }
 val colorSecond = context?.let { ContextCompat.getColor(it, R.color.colorSecond) }
 val colorThird = context?.let { ContextCompat.getColor(it, R.color.colorThird) }

 pieDataSet.colors = mutableListOf(colorFirst, colorSecond, colorThird)
like image 44
Manohar Avatar answered Feb 16 '23 08:02

Manohar